Esentially I want to create a data type uint1_t
. Is that even possible?
I know the size of the bool data type is one byte. But boolean values only need one bit. So does C essentially only use one bit for bool? If yes, then what does it do with the other seven. Using eight bits where one is sufficient seems such a waste of space.
Generally, the smallest addressable chunk of data in C is a byte. You can not have a pointer to a bit, so you can not declare a variable of 1 bit size.
A bit is a binary digit, the smallest increment of data on a computer. A bit can hold only one of two values: 0 or 1, corresponding to the electrical values of off or on, respectively. Because bits are so small, you rarely work with information one bit at a time.
It is not really possible to create a type that occupies one bit. The smallest addressable unit in C is the char
(which is by definition one byte and usually, but not necessarily, 8 bits long; it might be longer but isn't allowed to be shorter than 8 bits in Standard C).
You can approach it with :
typedef _Bool uint1_t;
or:
#include <stdbool.h> typedef bool uint1_t;
but it will occupy (at least) one byte, even though a Boolean variable only stores the values 0 or 1, false
or true
.
You could, in principle, use a bit-field:
typedef struct { unsigned int x : 1; } uint1_t;
but that will also occupy at least one byte (and possibly as many bytes as an unsigned int
; that's usually 4 bytes) and you'll need to use .x
to access the value. The use of bit-fields is problematic (most aspects of them are implementation defined, such as how much space the storage unit that holds it will occupy) — don't use a bit-field.
Including amendments suggested by Drew McGowen, Drax and Fiddling Bits.
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