Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a data type of length one bit in C

Tags:

c

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.

like image 666
Aymen Avatar asked Aug 12 '14 15:08

Aymen


People also ask

Is there a bit data type in C?

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.

Which data type only holds 1 bit of information a 0 or a 1?

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.


1 Answers

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.

like image 175
Jonathan Leffler Avatar answered Sep 22 '22 21:09

Jonathan Leffler