tags:

views:

240

answers:

3

I haven't dealt with programming against hardware devices in a long while and have forgotten pretty much all the basics.

I have a spec of what I should send in a byte and each bit is defined from the most significant bit (bit7) to the least significant (bit 0). How do i build this byte? From MSB to LSB, or vice versa?

+1  A: 

If the spec says MSB, then build it MSB. Otherwise if the spec says LSB, then build it LSB. Otherwise, ask for more information.

cbp
The spec says nothing. In some places the bits are listed from 0 to 7, in other places from 7 to 0. What is the most common way?
AngryHacker
According to this http://en.wikipedia.org/wiki/Most_significant_bit both ways exist. From my experience, 0 is the LSB.
Anna
+1  A: 

If you're going to write the whole byte at the same time, i.e. do a parallel transfer as opposed to a serial, the order of the bits doesn't matter.

If the transfer is serial, then you must find out which order the device expects the bits in, it's impossible to tell from the outside.

To just assemble a byte from eight bits, just use bitwise-OR to "add" bits, one at a time:

byte value = 0;

value |= (1 << n);  // 'n' is the index, with 0 as the LSB, of the bit to set.
unwind
+4  A: 

If these bits are being 'packeted' (which they usually are), then the order of bits is the native order, 0 being the LSB, and 7 being the MSB. Bits are not usually sent one-by-one, but as bytes (usually more than one byte...).

According to wikipedia, bit ordering can sometimes be from 7->0, but this is probably the rare case.

Anna