如何设置位?

How to set bits?

我有一个远程服务,它接收许多参数和一个整数来标记哪些为空:

byte<(param_count + 7)/8> null bitmap

我尝试过一个简单的实现,但由于我没有移位方面的经验,所以我不想展示它。

那么,给定一个布尔向量,我该如何创建我的位图?

如果 param_count 在编译时已知,您可以使用 std::bitset。这是一个例子:

// Define a bitmap with 'param_count + 7' elements
std::bitset<param_count + 7> b;

// Set the fifth bit, zero is the first bit
b[4] = 1;

// Convert to 'unsigned long', and the casting it to an int.
int a = int(b.to_ulong());

如果 param_count 在编译时 不是 ,则可以使用 std::vector<bool>。这是另一个例子:

// Define a bitmap with 'param_count + 7' elements
std::vector<bool> b(param_count + 7);

// Set the fifth bit, zero is the first bit
b[4] = 1;

// Convert to 'int'
int a = std::accumulate(b.rbegin(), b.rend(), 0, [](int x, int y) { return (x << 1) + y; });

std::vector<bool>int的转换取自this answer