gpt4 book ai didi

c++ - boolean 值的大小是多少? 1 位还是 1 字节?

转载 作者:行者123 更新时间:2023-11-30 21:13:57 26 4
gpt4 key购买 nike

printf("bool: %zu; true: %zu; 1: %zu\n", sizeof (bool), sizeof true, sizeof 1);

上面的代码产生

bool: 1; true: 1; 1: 4

我对 sizeof(1) 很满意,它是一个整数,因此大小为 4 个字节。但是bool (and true)只需要 1 "bit" 的大小,输出仍然是 1,即 1 个字节。

为什么会这样?

最佳答案

为了高效(打包)表示,请使用 std::bitset :

#include <bitset>

std::bitset<2000000> my_bits;

显然这仅适用于 C++。在 C 中,您必须自己显式地实现这一点,例如:

#include <stdint.h>
#include <limits.h>

uint8_t my_bits[2000000 / CHAR_BIT];

然后要访问各个位,您需要使用按位运算实现一些简单的内联函数。

关于c++ - boolean 值的大小是多少? 1 位还是 1 字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26095004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com