在c++中,
为什么布尔值是1字节而不是1位? 为什么没有4位或2位整数类型?
在为CPU编写模拟器时,我忽略了上述内容
在c++中,
为什么布尔值是1字节而不是1位? 为什么没有4位或2位整数类型?
在为CPU编写模拟器时,我忽略了上述内容
当前回答
因为在一般情况下,CPU以1字节作为基本单位分配内存,尽管一些CPU如MIPS使用4字节字。
但是vector以一种特殊的方式处理bool类型,vector<bool>为每个bool类型分配一个位。
其他回答
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的硬盘的地方是在古董店,它只是不值得麻烦打包比特。
从维基百科:
从历史上看,字节是的数字 用于编码单个字符的位 电脑里的文本,的确如此 因此,基本可寻址 许多计算机中的元件 架构。
因此字节是基本的可寻址单位,低于它计算机体系结构不能寻址。由于(可能)不存在支持4位字节的计算机,所以没有4位bool等。
然而,如果你可以设计这样一个体系结构,它可以将4位作为基本可寻址单位,那么你将拥有大小为4位的bool值,只在那台计算机上!
即使最小大小可能是1字节,你可以在1字节上有8位布尔信息:
http://en.wikipedia.org/wiki/Bit_array
Julia语言有BitArray,我读过c++实现。
因为在一般情况下,CPU以1字节作为基本单位分配内存,尽管一些CPU如MIPS使用4字节字。
但是vector以一种特殊的方式处理bool类型,vector<bool>为每个bool类型分配一个位。
考虑一下如何在模拟器级别实现这一点……
bool a[10] = {false};
bool &rbool = a[3];
bool *pbool = a + 3;
assert(pbool == &rbool);
rbool = true;
assert(*pbool);
*pbool = false;
assert(!rbool);