Smallest data type - can I define one bit variable?

I need only one bit to represent my data - 1 or 0. What is the best way to do this in C? The "normal" data types are too large.

+8
c types
source share
5 answers

You can create

typedef struct foo { unsigned x:1; } foo; 

Where did you tell the compiler that you will use only one bit of x .

But due to the layout of the packaging structure (the C standard is intentionally flexible so that compilers can optimize according to the architecture of the machine), it may well turn out that it still takes up as much memory space as a regular unsigned and the foo array should not be bitwise contiguous.

+10
source share

If you really want, you can create a structure with a member variable, bit field up to 1 bit.

Remember that the data type of the member variable must be unsigned , since you need to store 0 and 1 .

+5
source share

If you do not need millions of these flags or are limited by a memory limit, the best way is finally int .

This is because int usually matches the size of the natural word of your platform and can be correctly aligned by reference. The machine reads the word at any time, and the use of individual bits requires camouflage and offset, which takes time. On your typical PC with gigabytes of RAM, that would be just plain stupid.

If the memory problem is really a problem, bitfield structures exist.

+3
source share

A portable way is to define a variable in which individual bits are used as flags.

  #define FLAG_FOO 0 #define FLAG_BAR 1 // in case platform does not support uint8_t typedef unsigned char uint8_t; uint8_t flags; void flag_foo_set() { flags |= (1 << FLAG_FOO); } void flag_foo_clr() { flags &= ~(1 << FLAG_FOO); } uint8_t flag_foo_get() { return flags & (1 << FLAG_FOO); } 

For now, this may seem redundant compared to bit C fields. It is carried over to almost every ANSI C compiler.

+1
source share

Typically, the smallest addressable data block in C is a byte. You cannot have a pointer to a bit, so you cannot declare a variable of 1 bit. But, as Suraw Ghosh has already pointed out, you can declare bit codes where one bit is available directly.

0
source share

All Articles