如何根据"Endianness"将数据存储在位级别?

bak*_*kra 3 c pointers endianness bit

我读到有关Endianness的信息,并了解蹲...

所以我写了这个

main()
{
    int k = 0xA5B9BF9F;

    BYTE *b = (BYTE*)&k;    //value at *b is 9f
    b++;    //value at *b is BF
    b++;    //value at *b is B9
    b++;    //value at *b is A5
}
Run Code Online (Sandbox Code Playgroud)

k 等于 A5 B9 BF 9F

和(字节)指针" walk "o/p是9F BF b9 A5

所以我得到它的字节向后存储......好吧.

所以现在我想它是如何存储在BIT级别的......

我的意思是"9f"(1001 1111)存储为"f9"(1111 1001)?

所以我写了这个

int _tmain(int argc, _TCHAR* argv[])
{
    int k = 0xA5B9BF9F;
    void *ptr = &k;
    bool temp= TRUE;
    cout<<"ready or not here I come \n"<<endl;

    for(int i=0;i<32;i++)
    {   
        temp = *( (bool*)ptr + i );
        if( temp )
            cout<<"1 ";
        if( !temp)
            cout<<"0 ";
        if(i==7||i==15||i==23)
            cout<<" - ";
   }
}
Run Code Online (Sandbox Code Playgroud)

我得到一些随机输出

即使是没有.像"32"我没有任何理智.

为什么?

Ama*_*9MF 7

Just for completeness, machines are described in terms of both byte order and bit order.

The intel x86 is called Consistent Little Endian because it stores multi-byte values in LSB to MSB order as memory address increases. Its bit numbering convention is b0 = 2^0 and b31 = 2^31.

The Motorola 68000 is called Inconsistent Big Endian because it stores multi-byte values in MSB to LSB order as memory address increases. Its bit numbering convention is b0 = 2^0 and b31 = 2^31 (same as intel, which is why it is called 'Inconsistent' Big Endian).

The 32-bit IBM/Motorola PowerPC is called Consistent Big Endian because it stores multi-byte values in MSB to LSB order as memory address increases. Its bit numbering convention is b0 = 2^31 and b31 = 2^0.

在普通的高级语言使用下,位顺序通常对开发人员是透明的.使用汇编语言编写或使用硬件时,位编号确实起作用.


Ste*_*hen 5

您通过实验发现的Endianness指的是字节存储在对象中的顺序.

比特不会以不同的方式存储,它们总是8位,并且总是"人类可读"(高 - >低).

现在我们已经讨论过你不需要代码......关于你的代码:

for(int i=0;i<32;i++)
{   
  temp = *( (bool*)ptr + i );
  ...
}
Run Code Online (Sandbox Code Playgroud)

这不是你认为它正在做的事情.你正在迭代0-32,一个字中的位数 - 很好.但你的temp任务完全错了:)

重要的是要注意a bool*的大小与a 的大小int*相同BigStruct*.同一台机器上的所有指针大小相同 - 32位机器上的32位,64位机器上的64位.

ptr + i正在向地址添加i字节ptr.什么时候i>3,你正在阅读一个全新的词......这可能会导致一个段错误.

您想要使用的是位掩码.这样的事情应该有效:

for (int i = 0; i < 32; i++) {
  unsigned int mask = 1 << i;
  bool bit_is_one = static_cast<unsigned int>(ptr) & mask;
  ...
}
Run Code Online (Sandbox Code Playgroud)