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.