在c++中,

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

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


当前回答

字节是计算机中数字数据存储的较小单位。在计算机中,RAM有数百万个字节,每个字节都有一个地址。如果每个比特都有一个地址,那么计算机就可以少管理8倍的内存。

更多信息:维基百科

其他回答

字节是计算机中数字数据存储的较小单位。在计算机中,RAM有数百万个字节,每个字节都有一个地址。如果每个比特都有一个地址,那么计算机就可以少管理8倍的内存。

更多信息:维基百科

因为在一般情况下,CPU以1字节作为基本单位分配内存,尽管一些CPU如MIPS使用4字节字。

但是vector以一种特殊的方式处理bool类型,vector<bool>为每个bool类型分配一个位。

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

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

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

你可以有1位的bool型和4位和2位的int型。但这将导致一个奇怪的指令集,没有性能提升,因为这是一种不自然的方式来看待体系结构。“浪费”一个字节的大部分,而不是试图回收未使用的数据,实际上是有意义的。

根据我的经验,唯一一个把几个bool包进一个字节的应用程序是Sql Server。

Back in the old days when I had to walk to school in a raging blizzard, uphill both ways, and lunch was whatever animal we could track down in the woods behind the school and kill with our bare hands, computers had much less memory available than today. The first computer I ever used had 6K of RAM. Not 6 megabytes, not 6 gigabytes, 6 kilobytes. In that environment, it made a lot of sense to pack as many booleans into an int as you could, and so we would regularly use operations to take them out and put them in.

今天,当人们嘲笑你只有1gb的RAM,而你唯一能找到小于200gb的硬盘的地方是在古董店,它只是不值得麻烦打包比特。