问题描述
我正在尝试接收TCP套接字的消息并将其存储在uint8_t
数组中.我要接收的缓冲区长度为8个字节,并包含4个唯一值.字节1:值1为uint8_t,字节2-3:值2为uint16_t,字节4:值3为uint8_t,字节5-8:值4为无符号长整数.字节序是大字节序.
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);
但是第二个printf
打印出意外的值.我是否做了一些错误的操作以提取两个字节,或者我的打印功能有问题?
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?
推荐答案
也许像这样(大端)
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];
这篇关于如何从uint8_t数组中提取不同大小的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!