How does this work?
struct {
int a : 21;
int b : 11;
};
Are a and b two separate int variables or the same variable using different bit fields?
Bit Fields in C Language In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner.
What is a Bitwise Operator? The Bitwise Operator in C is a type of operator that operates on bit arrays, bit strings, and tweaking binary values with individual bits at the bit level. For handling electronics and IoT-related operations, programmers use bitwise operators. It can operate faster at a bit level.
Utilities Operating System Computer Hardware OS Designer End user Programmer Page 4 Copyright @ 2008 Ananda Gunawardena Bits, Bytes and Data Types A bit is the smallest unit of storage represented by 0 or 1. A byte is typically 8 bits. C character data type requires one byte of storage. A file is a sequence of bytes.
These are two separate variables in the struct
, one named a
and one named b
. However, they're sized so that a
should have 21 bits and b
should have 11 bits. Accessing one variable and manipulating it won't affect the other variable.
Hope this helps!
It's not completely clear what you mean by 'variables' here. If you mean piece of memory you can take address of, then the bitfields do not fit the description as they are part of an 'addressable storage unit'. If by 'variable' you mean "set of bits that I can store some value in", then both a and b look like any other field in a structure.
Enough semantic nit-picking, though. Let's go to the source:
ch 6.7.2.1 in C99 standard says:
10 An implementation may allocate any addressable storage unit large enough to hold a bit- field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.
So, depending on "addressable storage unit" compiler picks, your a and b may end up in different 'storage units', depending on compiler specifics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With