在c++中,

为什么布尔值是1字节而不是1位? 为什么没有4位或2位整数类型?

在为CPU编写模拟器时,我忽略了上述内容


当前回答

因为CPU不能寻址任何小于字节的东西。

其他回答

因为CPU不能寻址任何小于字节的东西。

从维基百科:

从历史上看,字节是的数字 用于编码单个字符的位 电脑里的文本,的确如此 因此,基本可寻址 许多计算机中的元件 架构。

因此字节是基本的可寻址单位,低于它计算机体系结构不能寻址。由于(可能)不存在支持4位字节的计算机,所以没有4位bool等。

然而,如果你可以设计这样一个体系结构,它可以将4位作为基本可寻址单位,那么你将拥有大小为4位的bool值,只在那台计算机上!

因为字节是语言中最小的可寻址单位。

但是你可以让bool值为1位,如果你有很多 如。在结构体中,像这样:

struct A
{
  bool a:1, b:1, c:1, d:1, e:1;
};

bool can be one byte -- the smallest addressable size of CPU, or can be bigger. It's not unusual to have bool to be the size of int for performance purposes. If for specific purposes (say hardware simulation) you need a type with N bits, you can find a library for that (e.g. GBL library has BitSet<N> class). If you are concerned with size of bool (you probably have a big container,) then you can pack bits yourself, or use std::vector<bool> that will do it for you (be careful with the latter, as it doesn't satisfy container requirments).

最简单的答案是;这是因为CPU以字节而不是位来寻址内存,按位的操作非常慢。

然而,在c++中可以使用位分配。对于位向量,有std::vector专门化,还有接受位大小条目的结构。