Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bitfields have to be integer?

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?

like image 753
zubergu Avatar asked Dec 25 '22 21:12

zubergu


2 Answers

Let's ask the converse question:

  • What types other than an integer type could a bit field be?

Let's review the options:

  1. void: not a value — wouldn't work.
  2. Pointers: but pointers on a machine are fixed size; you can't use 13 bits of a pointer and expect it to mean anything.
  3. Structures, unions: but then you aren't dealing with simple fields.
  4. That leaves 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.

like image 145
Jonathan Leffler Avatar answered Jan 07 '23 07:01

Jonathan Leffler


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.

like image 31
Robert Harvey Avatar answered Jan 07 '23 09:01

Robert Harvey