按位运算符和“ endianness”

Endianness与按位操作有关系吗? 是 合乎逻辑还是移位?

我正在做关于按位运算符的作业,我不知道它是正是反,我想我已经完全被 Endianess 所困扰了。也就是说,我正在使用一个小的 endian 机器(和大多数机器一样) ,但是这是否需要考虑,或者这是一个浪费的事实?

以防万一,我用的是 C。

28381 次浏览

You haven't specified a language but usually, programming languages such as C abstract endianness away in bitwise operations. So no, it doesn't matter in bitwise operations.

Endianness only matters for layout of data in memory. As soon as data is loaded by the processor to be operated on, endianness is completely irrelevent. Shifts, bitwise operations, and so on perform as you would expect (data logically laid out as low-order bit to high) regardless of endianness.

The bitwise operators abstract away the endianness. For example, the >> operator always shifts the bits towards the least significant digit. However, this doesn't mean you are safe to completely ignore endianness when using them, for example when dealing with individual bytes in a larger structure you cannot always assume that they will fall in the same place.

short temp = 0x1234;
temp = temp >> 8;


// on little endian, c will be 0x12, on big endian, it will be 0x0
char c=((char*)&temp)[0];

To clarify, I am not in basic disagreement with the other answers here. The point I am trying to make is to emphasise that although the bitwise operators are essentially endian neutral, you cannot ignore the effect of endianess in your code, especially when combined with other operators.

As others have mentioned, shifts are defined by the C language specification and are independent of endianness, but the implementation of a right shift may vary depending on iff the architecture uses one's complement or two's complement arithmetic.

It depends. Without casting the number into a new type, you can treat the endianness transparently.

However, if your operation involves some new type casting, then use your caution.

For example, if you want right shift some bits and cast (explicitly or not) to a new type, endianness matters!

To test your endianness, you can simply cast an int into a char:

int i = 1;


char *ptr;


...


ptr = (char *) &i;  //Cast it here


return  (*ptr);