在c++中,

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

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


当前回答

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

更多信息:维基百科

其他回答

您可以使用位字段来获取子大小的整数。

struct X
{
    int   val:4;   // 4 bit int.
};

尽管它通常用于将结构映射到精确的硬件预期位模式:

// 1 byte value (on a system where 8 bits is a byte)
struct SomThing   
{
    int   p1:4;   // 4 bit field
    int   p2:3;   // 3 bit field
    int   p3:1;   // 1 bit
};

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

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

即使最小大小可能是1字节,你可以在1字节上有8位布尔信息:

http://en.wikipedia.org/wiki/Bit_array

Julia语言有BitArray,我读过c++实现。

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

更多信息:维基百科

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).