为什么 C/C++ 中没有一位数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19333513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why there isn't a single bit data type in C/C++?
提问by iloahz
For bool
, it's 8 bit while has only true and false, why don't they make it single bit.
对于bool
,它是 8 位,而只有 true 和 false,他们为什么不将其设为一位。
And I know there's bitset
, however it's not that convenient, and I just wonder why?
而且我知道有bitset
,但是它不是那么方便,我只是想知道为什么?
回答by Igor Popov
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
.
主流CPU在硬件层面的基本数据结构是一个字节。对这些 CPU 中的位进行操作需要额外的处理,即一些 CPU 时间。这同样适用于bitset
。
回答by Albert
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:
不完全是为什么没有本机类型的答案。但是你可以在结构中得到一个 1 位类型,如下所示:
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).
因此,sizeof(A) == 1
如果没有填充(这可能是 的倍数sizeof(void*)
,即对于 32 位系统,可能是 4)。
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.
请注意,由于其他人陈述的原因,您无法获得指向任何这些字段的指针。这也可能是不存在本机类型的原因。