Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest data type - can I define a one bit variable? [duplicate]

Tags:

c

types

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

like image 543
Roy Avatar asked Jul 09 '15 07:07

Roy


People also ask

What is the smallest data type?

The smallest data type is a byte, which is 8 bits. Each bit can be a 0 or 1.

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.


2 Answers

You could create

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

Where you have told the compiler that you'll only be using one bit of x.

But due to structure packing arrangements (the C standard is intentionally flexible in order that compilers can optimise according to the machine architecture), it may well turn out that this still occupies as much space in memory as a regular unsigned and an array of foos doesn't have to be bitwise contiguous.

like image 58
Bathsheba Avatar answered Sep 23 '22 06:09

Bathsheba


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

Remember, the data type of the member variable needs to be unsigned, as you need to store 0 and 1.

like image 33
Sourav Ghosh Avatar answered Sep 24 '22 06:09

Sourav Ghosh