Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit order in C/C++

Tags:

c++

c

bit

I have to implement a protocol which defines data in 8bit words, which starts with the least significant bit (LSB) first. I want to realize this data with unsigned char, but I don't know what's the bit order of LSB and most significant bit (MSB) in C/C++, that could possible require swapping the bits.

Can anybody explain me how to find out an unsigned char is encoded: with MSB-LSB or LSB-MSB?

Example:

unsigned char b = 1;

MSB-LSB: 0000 0001 LSB-MSB: 1000 0000

like image 219
Dudero Avatar asked Sep 29 '11 12:09

Dudero


People also ask

What is the order of bits in a byte?

Bits within a byte are commonly numbered as Bit0 for the least significant bit and Bit7 for the most significant bit. Thus, bit numbering in a 32-bit integer will be left-to-right order in big-endian, and right-to-left in little-endian.

Does Endianness affect Bit order?

There is no endianness involved at bit level when it comes to data, only bit position matters when you give a meaning to the value of a byte, and LSB-0 is always 0x01, no matter it's a big endian machine or a little endian one. Byte values has nothing to do with how the machine treats a bit, most significant or not.

How do I extract a bit from an integer?

printf("int has %ud bits\n", sizeof(int) * 8); sizeof() returns the size in bytes of an integer, and then you multiply that result by 8 (bits per byte in 99.999% of cases)to get the size in bits of your integer, and therefore the size of the masks you have to apply.


2 Answers

Endian-ness is platform dependent. Anyway, you don't have to worry about actual bit order unless you are serializing the bytes, which you may be trying to do. In which case, you still don't need to worry about how individual bytes are stored while they're on the machine, since you will have to dig the bits out individually anyway. Fortunately, if you bitwise AND with 1, you get the LSB, regardless of storage order; bit-AND with 2 and you get the next most significant bit, and so on. The compiler will sort out what constants to generate in the machine code, so that level of detail is abstracted away.

like image 114
JustJeff Avatar answered Sep 29 '22 10:09

JustJeff


There is no such thing in C/C++. The least significant bit is -- well -- the least significant bit. Since the bits don't have addresses, there is no other ordering.

like image 22
undur_gongor Avatar answered Sep 29 '22 10:09

undur_gongor