0

我试图更好地理解按位运算符。我有许多类型uint32_t,我试图逐字节输出。这样做的代码是:

void printByteWise(uint32_t num) {

  printf("byte 1 = %u\n", (num & 0xFF000000));
  printf("byte 2 = %u\n", (num & 0x00FF0000));
  printf("byte 3 = %u\n", (num & 0x0000FF00));
  printf("byte 4 = %u\n", (num & 0x000000FF));
}

在上面的代码示例中说num是 9。那么字节数组应该像这样存储在内存中:(
09 00 00 00按地址升序排列)。如果是这样,输出应该是:
byte 1 = 09
byte 2 = 00
byte 3 = 00
byte 4 = 00
但我得到的输出是:

byte 1 = 0
byte 2 = 0
byte 3 = 0
byte 4 = 9

我在一个小端系统上,它是这样获得的:

int is_bigEndian() {
  int i = 1;
  char *low = (char *) (&i);
  return *low ? 0 : 1;
}  

这种行为正确吗?为什么我会看到这种行为?

4

2 回答 2

3

Remember, both of your operands are the same endianness.

On little endian, yes, 9 will be stored as 0x09000000. You are then masking with 0xFF000000, which will be stored in memory as 0x000000FF as will therefore be used in that pattern as the mask.

If you want to see the effect fully, do as Ali Veli says and iterate over memory byte-by-byte by using a char pointer.

于 2013-02-12T10:44:11.777 回答
0

使用按位运算符,您的操作数实际上是寄存器中的数字而不是内存中的数字。所以这里与字节顺序无关,这是预期的和正确的。

If you inspect the variable by casting it's address to char * or something and go over bytes by increasing the value of pointer, then you will be reading a byte from memory each time (let's say cache is transparent) and there you would see the effect of endianness.

于 2013-02-12T10:41:09.067 回答