Hexadecimal log in c

1 minute read

When you are network-programming, you can use logging function if you have special characters such as NULL, STX, ETX, etc., and if you have the wrong value, you can also use it for debugging. Of course, you can copy it and see it as UltraEdit, but it has the advantage of being able to see it directly on the log.

#define DIVISOR             10
#define HEX_BUFF            10240

void HexLog(char *data, int size);

void HexLog(char *data, int size)
{
    char *FNID = "HexLog";
    int i, j;
    long seq = 0, next;
    char _LOGBUFF[HEX_BUFF];
    char temp[16];

    if( size > HEX_BUFF )
        size = HEX_BUFF;

    printf("----------------------------- HEX DEBUG ---------------------------------\n");
    for (i = 0; i < (size / DIVISOR) + 1; i++) {
        if (seq >= size)
            break;
        memset(_LOGBUFF,    0x00,   HEX_BUFF);
        sprintf (temp, "%04ld: ", seq);
        strcat(_LOGBUFF,    temp);
        next = seq;

        for (j = 0; j < DIVISOR; j++) {
            if (seq >= size) {
                sprintf (temp, "     ");
                strcat(_LOGBUFF,    temp);
            }
            else
            {
                sprintf (temp, "0x%02x ", *(data + seq));
                strcat(_LOGBUFF,    temp);
                seq++;
            }
        }

        sprintf (temp, " : [ ");
        strcat(_LOGBUFF,    temp);

        for (j = 0; j < DIVISOR; j++)
        {
            if (next >= size)
            {
                strcat(_LOGBUFF, " ");
                continue;
            }

            if (*(data + next) < 0x20)
                strcat(_LOGBUFF, ".");
            else {
                sprintf (temp, "%c", *(data + next));
                strcat(_LOGBUFF, temp);
            }
            next++;
        }

        strcat(_LOGBUFF, " ]");
        printf("%s\n", _LOGBUFF);
    }

    printf("-------------------------------------------------------------------------\n");

    return;
}

Tags: ,

Categories:

Updated:

Leave a comment