【发布时间】:2020-07-09 05:07:38
【问题描述】:
我想以位为单位传输数据,所以我使用 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]
... => ...
我不知道为什么会这样。有人可以解释一下吗?
================================================ ==============================
问题已解决。该系统不是大端。我错了。
【问题讨论】:
-
data by bit unit- 但您打印的是字节,而不是位。看起来您确实想使用std::ostream::write。我不明白 - 解释一下到底是什么?why this happen- 会发生什么? -
@KamilCuk 你的意思是你推荐使用 ostream::write?
-
如果您通过网络发送数据,例如使用 UART 芯片,该芯片应该为您正确地对电线上的位进行排序,并将它们正确地呈现给另一端的接收者。我怀疑你可能想多了,“借了事”。您是否面临实际数据接收不正确的情况?
-
so i think this system is big endian- 你确定吗?最低有效字节(即65)排在第一位。you mean that you recommend- 我不“推荐”,我不明白你在做什么,你想做什么。我相信我误解了你的问题。 -
@KamilCuk 是的,你说得对。我错了。该系统是小端的。谢谢!
标签: c++ bit endianness memory-address char-pointer