我正在通过网络数据包接收一个简短的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("%dn", 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位臂,不允许访问。因此,请使用memcpy在调用NTOH之前将其变成正确尺寸的INT。
您已经混淆了索引。该数字是小endian中的0x0190,但是您的代码计算了 0x9001
,在签名的短片中也会导致左移到符号的整数溢出。
代码确实不是很便携,因为char
可能被签名或未签名。虽然大多数架构都具有未签名的字符,但事实是,大多数C程序都是为签名的Char Architecture -X86编写的。在那里,0x90被签名可能会导致狂野的意外结果。
因此,更便携的是
char testResponse[2] = {0x01, 0x90};
unsigned int tmp = (unsigned)testResponse[0] << 8 | (unsigned)testResponse[1];
short result = tmp; // implementation-defined behaviour
printf("%dn", result); // 400