Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a 3 bit variable as datatype in C? [duplicate]

Tags:

c

I can typedef char to CHAR1 which is 8 bits. But how can I make 3 bit variable as datatype?

like image 791
Ishmeet Avatar asked Jul 10 '15 11:07

Ishmeet


3 Answers

You might want to do something similar to the following:

struct
{
  .
  .
  .
  unsigned int fieldof3bits : 3;
  .
  .
  .
} newdatatypename;

In this case, the fieldof3bits takes up 3 bits in the structure (based upon how you define everything else, the size of structure might vary though).

This usage is something called a bit field.

From Wikipedia:

A bit field is a term used in computer programming to store multiple, logical, neighboring bits, where each of the sets of bits, and single bits can be addressed. A bit field is most commonly used to represent integral types of known, fixed bit-width.

like image 69
Jay Bosamiya Avatar answered Nov 03 '22 22:11

Jay Bosamiya


It seems you're asking for bitfields https://en.wikipedia.org/wiki/Bit_field Just be aware that for some cases it's can be safer just use char or unsigned char instead of bits (compiler specific, physical memory layout etc.)

Happy coding!

like image 20
Yury Schkatula Avatar answered Nov 03 '22 21:11

Yury Schkatula


typedef struct {

int a:3;
}hello; 

It is only possible when it is inside structure else it is not

like image 42
Sohil Omer Avatar answered Nov 03 '22 22:11

Sohil Omer