如何通过强制转换类型指针将字符数组转换为uint16_t

How to convert a char array to a uint16_t by casting type pointer?

本文关键字:转换 数组 uint16 字符 指针 何通过 类型      更新时间:2023-10-16
char bytes[2];
bytes[0] = 0; //0x00
bytes[1] = 24; //0x18
uint16_t* ptrU16 = (uint16_t*)bytes; // I expect it points to the memory block: 0x18
cout << *ptrU16 << endl;  // I expect 24, but it is 6144

我的代码出了什么问题?

你有一台小端序机。 6144 0x1800.当你的机器表示内存中0x0018的 16 位值时,它会将 0x18 字节放在第一位,0x00 字节放在第二位,因此当您将双字节序列0x0018解释为uint16_t时,它会为您提供6144(即 0x1800 (,而不是24(即 0x0018 (。

如果更改为:

bytes[0] = 24; 
bytes[1] = 0;

您可能会看到预期的结果。

如果你真的想得到你期望的结果,那么你要么必须手动计算它,例如:

uint16_t n = (bytes[1] << 8) + bytes[0];

或者,更一般地说:

char bytes[] = {0x18, 0x00};
uint16_t n = 0;
for ( size_t i = 0; i < 2; ++i ) {
    n += bytes[i] << 8 * i;
}
std::cout << n << std::endl;

或者你可以使用像ntohs()这样的函数,因为网络字节顺序是大端序。

您可能需要研究ntohs()函数。("网络到主机字节顺序转换"(。您以大端模式插入数据,传统上这也是网络字节顺序。无论你在哪个主机上,ntohs(( 函数都应该返回你期望的值。有一个镜像功能,用于从主机到网络顺序。

#include <arpa/inet.h>
...
cout << htons(*ptrU16) << endl;

应该可以跨系统工作并可移植。(即应该在Power,ARM,X86,Alpha等上工作(。