首页 > 解决方案 > 我想按字节单位传输数据,我认为这是关于字节序的

问题描述

我想按位单位传输数据,所以我使用 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]
    ...       =>       ...

我不知道为什么会这样。有人可以解释一下吗?

==================================================== ===========================

问题解决了。该系统不是大端。我错了。

标签: c++bitendiannessmemory-addresschar-pointer

解决方案


当我按字节单元访问数据时,第一个地址指向数据显示'65',所以我认为这个系统是大端的。

不,这意味着它是小端。最低有效字节位于最低地址,值为 65。

关于通过逐字节复制普通旧数据在相同类型的指针之间“传输”数据,除非您在系统之间进行,否则字节序无关紧要。它只在解释中很重要,并且( *(p + 0) << 24 ) | ( *(p + 1) << 16 ) | ( *(p + 2) << 8 ) | *(p + 3)是大端解释,所以会给你错误的结果。你已经知道*p65*p就是 65,所以即使你忘记了大或小是什么意思,*(p + 0) << 24也是错误的。

如果您确实想在系统之间逐字节传输,则可以使用 posix 函数hton*X*()ntoh*X*()不同的整数类型从主机转换为网络或从网络转换为主机字节顺序。


推荐阅读