user3577756 user3577756 - 1 month ago 7
C Question

How to extract values of different sizes from an array of uint8_t?

I am trying to receive a message of a TCP socket and store it in an

uint8_t
array.
The buffer I am to receive is to be 8 bytes long and contains 4 unique values.
Byte 1: value 1 which is a uint8_t, Byte 2-3: value 2 which is a uint16_t, Byte 4: value 3 which is a uint8_t, Byte 5-8: value 4 which is an unsigned long.
Endiannessis big endian order.

int numBytes = 0;
uint8_t buff [8];
if ((numBytes = recv(sockfd, buff, 8, 0)) == -1)
{
perror("recv");
exit(1);
}

uint8_t *pt = buff;
printf("buff[0] = %u\n", *pt);
++pt;
printf("buff[1] = %u\n", *(uint16_t*)pt);


But the second
printf
prints out an unexpected value. Have I done something incorrectly to extract the two bytes or is something wrong with my print function?

Answer

Perhaps like this (big-endian)

uint8_t buff [8];
// ... 
uint8_t       val1 = buff[0];
unit16_t      val2 = buff[1] * 256 + buff[2];
unit8_t       val3 = buff[3];
unsigned long val4 = buff[4] * 16777216 + buff[5] * 65536 + buff[6] * 256 + buff[7];
Comments