tannoy connect
tannoy connect

Reputation: 385

Is shifting bits dependent on the endianness?

I understand that if I want to do 2n then I can do (0x1ul << n) and I will get the result.

What if the processor is big-endian? If I do a shift to the left, will it not result in the wrong output? Will the (0x1ul << n) be wrong i.e. not equal to 2n when we have a big-endian architecture? How can I prove that?

Upvotes: 4

Views: 460

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215387

The source of your confusion seems to be over what "left" and "right" mean. In the sense of the << and >> operators, their meanings are in the usual arithmetic sense where digits are written from least significant on the right to most significant on the left. In fact C defines these operators as arithmetic operators, not bitwise operators, as multiplication or division by an appropriate power of two for the inputs they're defined on.

In particular, these operators do not move bits "left" or "right" "in memory"; they don't even act on memory, but on values. Sometimes it makes sense to think of using them to move bytes around in memory (with shifts that are multiples of 8), and in that case, whether you need << or >> to move bytes "left" "in memory" (in representation) depends on whether the representation is little- or big-endian. You see this come up in places like this implementation of memcpy for ARM that works on older chips without support for misaligned access.

Upvotes: 2

chux
chux

Reputation: 154280

Will the (0x1ul << n) be wrong i.e. not equal to 2n when we have a big-endian architecture?

No, along as 0x1ul << n fits in an unsigned long, all is well. Byte (or bit) endian-ness is not relevant.

Upvotes: 0

Sourabh Choure
Sourabh Choure

Reputation: 733

Endianness only makes sense when you’re breaking up a multi-byte quantity and are trying to store the bytes at consecutive memory locations. However, if you have a 32-bit register storing a 32-bit value, it makes no sense to talk about endianness. The register is neither big-endian nor little-endian; it’s just a register holding a 32-bit value. The rightmost bit is the least significant bit, and the leftmost bit is the most significant bit.

Same in this situation, once the value of the variable is loaded from the memory to a register for shifting, it doesn't matter which endian it is, all it does is a shift as specified and store back in the memory.

Reference: Writing endian-independent code in C

Upvotes: 4

Related Questions