整数如何存储在内存中?

Alc*_*ott 3 c++ endianness

当我读一篇关于Big/Little Endian的文章时,我很困惑.

代码如下:

#include <iostream>
using namespace std;

int i = 12345678;

int main()
{
    char *p = (char*)&i;  //line-1

    if(*p == 78)  //line-2
        cout << "little endian" << endl;
    if(*p == 12)
        cout << "big endian" << endl;

}
Run Code Online (Sandbox Code Playgroud)

题:

  1. 在第1行中,我可以使用static_cast<char*>(&i)?进行转换吗?

  2. 在第2行中,根据代码,如果它是little-endian,则78存储在最低字节中,否则12存储在最低字节中.但我认为,i = 12345678;将以二进制形式存储在内存中.

    如果它是little-endian,那么i二进制文件的最后一个字节将存储在最低字节中,但我不明白的是它如何保证最后一个字节i78

    就像,如果i = 123;,然后i是二进制文件01111011,是否可以保证在little-endian 23中存储在最低字节中?

Fre*_*Foo 9

  1. 我更喜欢reinterpret_cast.

  2. little-endian和big-endian指的是字节(即8位量)存储在内存中的方式,而不是两位小数.如果i有值0x12345678,则可以检查0x780x12确定字节序,因为两个十六进制数字对应于一个字节(在我编程的所有硬件上).