c++ - 我想按字节单位传输数据,我认为这是关于字节序的
问题描述
我想按位单位传输数据,所以我使用 char* 变量访问数据。这是我的代码。
int main()
{
//initiate int variable and casting with char*
int a = 65;
cout << a << endl;
char* p = reinterpret_cast<char*>(&a);
cout << "------------------" << endl;
//check char* p is pointing &a
cout << &a << endl;
printf("0x%x\n", p);
cout << "------------------" << endl;
//access int variable with byte unit
cout << (int)*(p + 0) << endl;
cout << (int)*(p + 1) << endl;
cout << (int)*(p + 2) << endl;
cout << (int)*(p + 3) << endl;
cout << "------------------" << endl;
//initiate int variable and assemble with char* access in way 1
int* b = new int(0);
*b = *(p + 0) << 24;
*b += *(p + 1) << 16;
*b += *(p + 2) << 8;
*b += *(p + 3);
cout << *b << endl;
cout << "------------------" << endl;
//initiate int variable and assemble with char* access in way 2
*b = *(p + 0);
*b += *(p + 1) << 8;
*b += *(p + 2) << 16;
*b += *(p + 3) << 24;
cout << *b << endl;
return 0;
}
并像这样输出。
65 -> variable a is 65
------------------
0x61ff04
0x61ff04 -> char* p is pointing right
------------------
65
0
0
0 -> access with byte unit
------------------
1090519040 -> way 1
------------------
65 -> way 2
当我按字节单元访问数据时,第一个地址指向数据显示'65',所以我认为这个系统是大端的。
所以我想如果我想将'a'数据传输到变量'b',那么*(p + 0)数据应该首先像方式1一样,但结果不正确。*(p+0) 最后 - 方式 2,显示正确的值。
以简单的方式思考,我想我是像这样在直接内存中点对点传输数据
variable a => variable b
[0x000000] => [0x100000]
[0x000001] => [0x100001]
[0x000002] => [0x100002]
... => ...
我不知道为什么会这样。有人可以解释一下吗?
==================================================== ===========================
问题解决了。该系统不是大端。我错了。
解决方案
当我按字节单元访问数据时,第一个地址指向数据显示'65',所以我认为这个系统是大端的。
不,这意味着它是小端。最低有效字节位于最低地址,值为 65。
关于通过逐字节复制普通旧数据在相同类型的指针之间“传输”数据,除非您在系统之间进行,否则字节序无关紧要。它只在解释中很重要,并且( *(p + 0) << 24 ) | ( *(p + 1) << 16 ) | ( *(p + 2) << 8 ) | *(p + 3)
是大端解释,所以会给你错误的结果。你已经知道*p
65*p
就是 65,所以即使你忘记了大或小是什么意思,*(p + 0) << 24
也是错误的。
如果您确实想在系统之间逐字节传输,则可以使用 posix 函数hton*X*()
将ntoh*X*()
不同的整数类型从主机转换为网络或从网络转换为主机字节顺序。
推荐阅读
- arrays - 从多个标准中查找以显示最接近的答案
- postgresql - Osm2pgsql 由于错误而失败:无法检测文件格式
- sharepoint - Sharepoint 2016 本地详细信息项目版本字段信息
- php - 如何在 Laravel 中存储多选值
- node.js - 填充单个嵌入文档
- angular - Angular 6 - HTTP Post 上未添加标头
- javascript - html 5画布未显示在iOS移动Safari上
- ckeditor - CKEditor 5 保存选定的文本并在恢复内容后再次将其设置为选定
- angular - 角内化翻译文件上传按钮文本
- python - Python2将exec从不合格转换为合格