繁体   English   中英

为什么位反转了?

[英]Why are the bits reversed?

在下面的代码中,我试图将2个字节的int存储在2个char 然后,我尝试在屏幕上显示我存储的号码。 这些部分工作得很好。

另一方面,如果我尝试查看存储的数字的二进制形式,我将无法获得预期的结果。 256给我00000000 1而正确的是10000000 0

unsigned int num = 256;
unsigned int pos = 0;

unsigned char a[2] = {num << pos, ((num << pos) & 0xFF00) >> 8};
//we store the number in 2 bytes

cout << (((unsigned int)a[0] + ((unsigned int)a[1] << 8)) >> pos) << endl;
//we check if the number we stored is the num

for(int i = 0; i < 2; i++)//now we display the binary version of the number
{
    for(int j = 0; j < 8; j++)
        cout << ((a[i] >> j)&1);
    cout << " ";
}

有人可以解释我做错了吗?

更改:

cout << ((a[i] >> j)&1);

至:

cout << ((a[i] >> (8-j-1))&1);

或更改:

for(int j = 0; j < 8; j++)

至:

for(int j = 8-1; j >= 0; j--)
unsigned char a[2] = {num << pos, ((num << pos) & 0xFF00) >> 8};

表示您将低位存储在a [0]中,将高位存储在a [1]中。

256 = 1 00000000
a[0] = 00000000
a[1] = 00000001

并且for(int j = 0; j < 8; j++) (最低有效位在前)应该是for(int j = 7; j >=0; j--) (最高有效位在前)

数字首先以最低有效位存储在内存中。

这样想:数字456在10 ^ 0处有6,在10 ^ 1处有5, 依此类推。将其存储为“ 654”(在字符串的第i个字符对应于第10个第i个数字)。

计算机以相同的方式存储数字:数字的第一位代表第2 ^ 0位,第i位到第2 ^ i位。

该规则实际上在Big Endian中是半破的,这是一种将十六进制数字从最大到最小存储的方式(人类可读的方式)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM