Home > OS >  Is the value of my conversion correct? Hex string to byte array
Is the value of my conversion correct? Hex string to byte array

Time:11-11

I've the following issue: from a socket, I receive an hexadecimal string, then I convert it to a byte array and save it into a uint8_t array. Here is the conversion function (it works):

static size_t convert_hex(uint8_t *dest, size_t count, const char *src)

    {
    size_t i = 0;
    int value;
    for (i; i < count && sscanf(src   i * 2, "%2x", &value) == 1; i  )
    {
        dest[i] = value;
    }
    return i;
}

Then, I reconvert this byte array to an hex string, only to know if the conversion was correct. The conversion is correct beacuse the hexadecimal string received from the socket (before the conversion to a byte array), is the same string after the conversion from uint8_t to hexadecimal string: here is the flow -> HEX_STRING -> UINT8_T ARRAY -> HEX_STRING

static size_t convert_hex_inv(char *dest, size_t count, const uint8_t *src)
{
    size_t i = 0;
    for (i = 0; i < count && sprintf(dest   i * 2, "X", src[i]) == 2; i  )
        ;
    return i;
}

Anyway, when I print the byte array, the result seems stange, because it appears to me too short. Where is the problem? Is it in the print?

n = recvfrom(sockfd, (char *)buffer, 1024, 
            MSG_WAITALL, ( struct sockaddr *) &cliaddr,
            &len);
buffer[n] = '\0';
printf("[SKT]\tHex String: %s. Message Type: %c\n", buffer, buffer[3]);
uint8_t uint8_payload[2048];
uint16_t uint_size = convert_hex(uint8_payload, n, buffer);
printf("[SKT]\tByte Array: %" PRIu8 "\n", uint8_payload);
char hex_array[n];
convert_hex_inv(hex_array, uint_size, uint8_payload);
printf("[SKT]\tHex String: %s\n", hex_array);
}

The result is:

[2021-11-11 12:02:23.410] [SKT] Hex String : 0201000000A8C0000000540000000000000000000000000446E88CEB36E7806FFEFFE000192E5B0F001C029FFFE30101F7D0000C003C000D000401D1C0FF6C3C80
[2021-11-11 12:02:23.410] [SKT] Byte Array: 4152851276 -> **THIS VALUE IS QUITE STRANGE**
[2021-11-11 12:02:23.410] [SKT] Hex String: 0201000000A8C0000000540000000000000000000000000446E88CEB36E7806FFEFFE000192E5B0F001C029FFFE30101F7D0000C003C000D000401D1C0FF6C3C80

CodePudding user response:

With the statement

printf("[SKT]\tByte Array: %" PRIu8 "\n", uint8_payload);

You don't print the contents of the array uint8_payload. Instead you print the pointer to its first element (remember that uint8_payload will decay to &uint8_payload[0]).

To print all the elements you need to do it one by one in a loop.

  • Related