整数如何存储在内存中? [英] how are integers stored in memory?
问题描述
我在阅读关于Big / Little Endian的文章时感到困惑。
I'm confused when I was reading an article about 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;
}
问题:
-
在第一行,我可以使用
static_cast< char *>(& i)
?
在第二行,根据代码,如果是小端字符串,则 78
存储在最低字节中,否则 12
存储在最低字节中。但我认为, i = 12345678;
将以二进制的形式存储在内存中。
In line-2, according to the code, if it's little-endian, then 78
is stored in the lowest byte, else 12
is stored in the lowest byte. But what I think is that, i = 12345678;
will be stored in memory in binary.
-endian,那么 i
的最后一个字节将存储在最低字节,但是我不明白是如何保证最后一个字节 i 是
78
?
If it's little-endian, then the last byte of i
's binary will be stored in the lowest byte, but what I don't understand is how can it guarantee that the last byte of i
is 78
?
code> i = 123; ,则 i
的二进制是 01111011
,可以保证在小端字节中, 23
存储在最低字节中吗?
Just like, if i = 123;
, then i
's binary is 01111011
, can it guarantee that in little-endian, 23
is stored in the lowest byte?
推荐答案
I'd prefer a
reinterpret_cast
.
Little- endian和big-endian指的是方式字节,即8位数量,存储在存储器中,而不是两位十进制数量。如果 i
的值为 0x12345678
,则可以检查 0x78
和 0x12
以确定字节顺序,因为两个十六进制数字对应于一个字节(在我编程的所有硬件上)。
Little-endian and big-endian refer to the way bytes, i.e. 8-bit quantities, are stored in memory, not two-decimal quantities. If i
had the value 0x12345678
, then you could check for 0x78
and 0x12
to determine endianness, since two hex digits correspond to a single byte (on all the hardware that I've programmed for).
这篇关于整数如何存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!