Every book I searched, every tutorial on the internet and every q&a on SO says, that bitfields have to be integer type. Why is that?
Let's ask the converse question:
Let's review the options:
void
: not a value — wouldn't work.float
or double
, but those are carefully designed formats and you can't simply use 13 bits out of a double
(or float
) and expect it to mean anything.So, after you've gone through the options, you are left with the various types of integer: char
, short
, int
, long
, long long
(in signed and unsigned forms), and _Bool
. Of these options, the standard specifies that you can use _Bool
, unsigned int
, signed int
and 'plain' int
:
ISO/IEC 9899:2011 §6.7.2.1 Structure and union type specifiers
¶5 A bit-field shall have a type that is a qualified or unqualified version of
_Bool
,signed int
,unsigned int
, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted.
The behaviour of 'plain' int
is implementation defined: it may be signed or unsigned (roughly like 'plain' char
can be signed or unsigned). So, the comment by jxh is correct; I was careless quoting too many types (but I've rephrased things so that it isn't so misleading).
Note that most of the behaviour of bit-fields is implementation defined; beyond the notation, there is very little that is specified by the standard.
Integers are a simple set of weighted bits. They are quiet, unassuming, and lend themselves readily to bit manipulation.
Almost every other data type is subject to some sort of interpretation: floating point numbers have two parts, a mantissa and an exponent; strings are ... well, strings of bytes (or Unicode values). A structure, or a pointer to an array, can represent almost anything.
As an example, I can easily store 32 bits in an integer, and retrieve them like so (c-like pseudocode):
int GetBit(int field, int position)
{
return field & 1 << position;
}
Where the return value is either 1 or 0, stored in an integer.
A byte (eight bits) is sort of the lowest common denominator in a computer system; computers won't let you retrieve quantities of bits smaller than that directly, and most computers nowadays retrieve bits in multi-byte quantities. A 32 bit computer retrieves... well, 32 bits at a time; a 32 bit integer, which is where our conversation began.
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