Why there isn't a single bit data type in C/C++?
Solution 1
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
.
Solution 2
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.
iloahz
Updated on July 25, 2022Comments
-
iloahz almost 2 years
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? -
KillianDS over 10 yearsActually the basic data structure is usually a word, which are often enough 4 (32-bit), 8 (64 bit) or even more (SSE for example) bytes in width. per-byte operations are often faked inside of those bigger word operations and are sometimes even slower than native word operations, similar to what you say about bits. Do not confuse the basic data structure of your memory (e.g. byte addressable) with that of your CPU.