Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there isn't a single bit data type in C/C++? [duplicate]

For bool, it's 8 bit while has only true and false, why don't they make it single bit.

And I know there's bitset, however it's not that convenient, and I just wonder why?

like image 326
iloahz Avatar asked Oct 12 '13 11:10

iloahz


People also ask

Is there a bit data type in C?

Declaration of bit-fields in C It is an integer type that determines the bit-field value which is to be interpreted. The type may be int, signed int, or unsigned int. The member name is the name of the bit field.

Which data type uses only one bit?

boolean: The boolean data type has only two possible values: true and false . Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

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.

What is the smallest 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.


2 Answers

The basic data structure at the hardware level of mainstream CPUs is a byte. Operating on bits in these CPUs require additional processing, i.e. some CPU time. The same holds for bitset.

like image 105
Igor Popov Avatar answered Oct 19 '22 11:10

Igor Popov


Not exactly an answer to why there is not a native type. But you can get a 1-bit type inside of a struct like this:

struct A {
  int a : 1; // 1 bit wide
  int b : 1;
  int c : 2; // 2 bits
  int d : 4; // 4 bits
};

Thus, sizeof(A) == 1 could be if there wouldn't be the padding (which probably takes it to a multiple of sizeof(void*), i.e. maybe 4 for 32bit systems).

Note that you cannot get a pointer to any of these fields because of the reasons stated by the other people. That might also be why there does not exist a native type.

like image 36
Albert Avatar answered Oct 19 '22 13:10

Albert