5 ms·
For packed structures, C already has bit fields. Example (from https://en.cppreference.com/w/cpp/language/bit_field https://en.cppreference.com/w/cpp/language/b
by Someone 7y ago
For packed structures, C already has bit fields. Example (from https://en.cppreference.com/w/cpp/language/bit_field https://en.cppreference.com/w/cpp/language/bit_field):
struct S {
// will usually occupy 2 bytes:
// 3 bits: value of b1
// 2 bits: unused
// 6 bits: value of b2
// 2 bits: value of b3
// 3 bits: unused
unsigned char b1 : 3, : 2, b2 : 6, b3 : 2;
};
This is more aimed at large integers.
- gray_-_wolf 7y agoKinda important part mentioned in the link is > Adjacent bit field members may be packed to share and straddle the individual bytes. So it might not be packed. Ofc it usually is, at least on gcc and such.
- hermitdev 7y agoI think the bigger issue in regards to networking is ordering, not the (lack of) packing. I don't think the ordering is guaranteed and probably depends on CPU architecture (e.g. big vs little endian), not necessarily compiler.
- gdwatson 7y agoIn practice, little-endian machines have the first bit field in the least-significant bits of the data type they fit into (usually but not always an int), and big-endian machines have the first bit field in the most-significant bits.
- drblast 7y agoI'm pretty sure the exact layout is not guaranteed in this case, so while the above code may work in many cases it's not possible to represent all data structures like this, particularly if the bits are not byte or machine word aligned. I don't think the standard even guarantees which bits in an integer the bitfields will be stored. That's important for network protocols.
- zamadatix 7y ago"so it's not just limited to a couple of small sized bitflag style things." The examples I gave are integers you may have to compare or manipulate not just bitfields to copy. I also disagree this is aimed at large integers based on the examples of the syntax in the article commonly being <16 bits, sometimes <8, while the examples I cited had non power of 2 use cases up to 48 bits.