gpt4 book ai didi

在 C 中将 2 个字节组合成一个 short int

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:52 25 4
gpt4 key购买 nike

我通过网络数据包接收到一个 short int,这意味着它将以网络字节顺序(big endian)中的 2 个字节的形式出现。

我想将我收到的两个字节组合成我机器上的一个 short int 变量,这是小端字节顺序。

例子:

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。

关于在 C 中将 2 个字节组合成一个 short int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com