如何通过强制转换类型指针将字符数组转换为uint16_t
How to convert a char array to a uint16_t by casting type pointer?
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等上工作(。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何在C++中将数组转换为矢量指针
- 将矢量<T>转换为矢量<数组<T>>
- JSON转换为nlohmann JSON-lib中的结构数组
- 将C++中的数组转换为字符串
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 将 int 数组转换为 std::vector<int*>
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 将链表转换为指针数组时出错
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 将浮点数转换为无符号字符数组并打印出来
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 在 c++ 中动态强制转换 ** 数组
- 返回并强制转换数组指针(错误:数组下标的类型..无效)
- 用于递归模板求值的强制转换数组类型
- node.js中使用node-gyp的转换数组
- 如何转换数组中的参数列表