我正在通过网络包接收一个短的int,这意味着它将以网络字节顺序(big endian)来表示2个字节。
我想把我收到的两个字节合并成一个短的int变量,在我的机器上,这是一个小的endian字节顺序。
例子:

short int test = 400; //0x190 in big endian, 0x9001 in little endian
char testResponse[2] = {0x01, 0x90};
//here is my attempt
short int result = testResponse[1] << 8 | testResponse[0];
printf("%d\n", result); //-28671 when expecting 400

任何帮助都将不胜感激!

最佳答案

#include <arpa/inet.h>
#include <string.h>

int16_t result;
memcpy(&result, testResponse, sizeof(int16_t));
result = (int16_t)ntohs((uint16_t)result);

一些平台,如32位arm,不允许未对齐的访问。所以在调用ntoh之前,请使用memcpy将其转换为正确大小的int。

07-24 09:44
查看更多