我想按字节为单位传输数据,我认为这与字节序有关

问题描述 投票:0回答:1

我想按位单位传输数据,所以我使用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++ bit endianness memory-address char-pointer
1个回答
0
投票

当我按字节为单位访问数据时,第一个地址指向数据显示为'65',因此我认为该系统为大端字节序。

不,这意味着它是小端的。最低有效字节在最低地址中,值65。

关于通过在字节之间逐字节复制原始数据来在相同类型的指针之间“传输”数据,除非您要在系统之间进行访问,否则字节序无关紧要。仅在解释中很重要,( *(p + 0) << 24 ) | ( *(p + 1) << 16 ) | ( *(p + 2) << 8 ) | *(p + 3)是大尾数法解释,因此会给您错误的结果。您已经知道*p为65 *p为65,所以即使您忘记了大或小的意思,*(p + 0) << 24都是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.