Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operators and "endianness"

Does endianness matter at all with the bitwise operations? Either logical or shifting?

I'm working on homework with regard to bitwise operators, and I can not make heads or tails on it, and I think I'm getting quite hung up on the endianess. That is, I'm using a little endian machine (like most are), but does this need to be considered or is it a wasted fact?

In case it matters, I'm using C.

like image 774
Frank V Avatar asked Jun 24 '09 23:06

Frank V


People also ask

Does endianness affect Bitwise Operators?

So no, it doesn't matter in bitwise operations.

What is meant by endianness?

Endianness is a term that describes the order in which a sequence of bytes is stored in computer memory. Endianness can be either big or small, with the adjectives referring to which value is stored first.

What is the point of endianness?

Going back to the Wikipedia article, the stated advantage of big-endian numbers is that the size of the number can be more easily estimated because the most significant digit comes first.

How do you convert endianness?

"I swap each bytes right?" -> yes, to convert between little and big endian, you just give the bytes the opposite order. But at first realize few things: size of uint32_t is 32bits, which is 4 bytes, which is 8 HEX digits. mask 0xf retrieves the 4 least significant bits, to retrieve 8 bits, you need 0xff.


2 Answers

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.

like image 92
Michael Avatar answered Oct 17 '22 01:10

Michael


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.

like image 27
1800 INFORMATION Avatar answered Oct 16 '22 23:10

1800 INFORMATION