1

I have a storage of n bytes (in my case a QByteArray in Qt, but i think the question is more a general question).

I have a class that operates on that storage and stores different kind of data types at any bit position in that bit field. It does that either in big endian or little endian order, depending on a parameter.

So far, no issues showed up. I exchange data over a can bus via such constructed bit fields. No I am implementing storing values in arbitrary length in bits (as long as they fit in).

This is easy for little endian values, as i can simply trim the leading zeros, and also leading ones when it comes to negative numbers.

But, when I think about how the correct way is to do that for a big endian value, I am a bit confused how to pack the values correctly.

For example, assuming I have the bit storage 0bXXXXXXXXXXXXXXXX and I want to store the value 0x0123 at bit offset 4, occupying 9 bits:

In little endian, I simply write the resulting 0b100100011 into my storage: 0bXXX100100011XXXX

In big endian, I end up having the value 0x2301. Is the correct way to pack that value that I trim the zeros in the first non-zero byte (from the right) to fit the 9 bits?

So this would lead to a value of 0x47 ending up having a resulting storage layout of 0bXXX001000111XXXX.

Is that the correct way to do this?

Thanks in advance.

darkmattercoder
  • 325
  • 6
  • 26
  • I am also confused: Why do you want to store some data as little endian and others as big endian? Why don't you select one storage scheme and convert the "wrong" data to the chosen scheme? – Reinhard Männer Nov 13 '19 at 21:08
  • Because that's what someone in his endless madness decided would be a good thing to have, years ago. A message payload byte stream which may contain both little endian and big endian coded values. No way for me to change that in any way :-/ – darkmattercoder Nov 13 '19 at 22:09
  • Endianness is a property of hardware. It has nothing to do with bits. It's about order of bytes within larger uniits (words etc). You almost never care about endianness. Certainly never if all you have is bytes. – n. m. could be an AI Nov 14 '19 at 17:04

1 Answers1

2

In your example, you want to transfer (as an example) a 2-byte number (0x0123) with 9 bits only.
This number can be transferred as little endian (0b00000001 followed by 0b00100011) or as big endian (0b00100011 followed by 0b00000001).
But since you have to represent it by 9 bits only, one has to drop leading zeroes (for positive numbers) or leading ones (for negative numbers). This means, the number to be transferred is in your example 0b100100011, i.e. the remainder of the higher value byte is 0b1, and the lower value byte is 0b00100011.
Thus the little endian representation is 0b100100011, and the big endian representation is 0b001000111, as you said.
PS: This is my personal opinion; I don't know if there is a official definition.

Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116