4 ms·
Unfortunately this cannot be used to pack an integer that is sent over the wire or to produce a register for a hardware peripheral. Basically this is not a vali
by dokem 8y ago
Unfortunately this cannot be used to pack an integer that is sent over the wire or to produce a register for a hardware peripheral. Basically this is not a valid substitution for most use cases of bit packing and can only be used to save a bytes of memory without reverting to undefined behavior. ie, casting this memory to a byte/int is undefined. The language does not define that the first field will be the lsb, msb or some arbitrary bit. The reason "many programmers don't know this" is because its a mostly useless language feature.
- Animats 8y agoPortability is a problem. There is this: Microsoft Specific The ordering of data declared as bit fields is from low to high bit. END Microsoft Specific[1] In practice, everybody does it that way. For fields only one byte wide, this isn't an issue for major compilers. NTP has been using this for decades without problems. But for structs more than one byte wide, there are little-endian/big endian problems. Just like with the numeric types. This is only an issue if you intend to write the bitfield to a network, file, or device. Locally, you usually don't care about the representation. [1] https://docs.microsoft.com/en-gb/cpp/cpp/cpp-bit-fields https://docs.microsoft.com/en-gb/cpp/cpp/cpp-bit-fields
- kolpa 8y agoThe OP also is not a valid substitution for "most" (by what metric, anyway?) uses of bit packing. The network wire doesn't need a C++ ABI-compatible object, and clearly isn't portable when communicating between systems running different software. For transmitting data over network, convert from local format to network format in transit. > can only be used to save a bytes of memory Yes, that's what "packing" is for.
- dokem 8y agoI think you are missing my points. This language feature cannot be used to eg, create a TCP header. It has nothing to do with the C++ ABI. And no, bit packing is not for memory saving, eg MISRA disallows bitpacking for the purpose of space saving.