ruipacheco
ruipacheco

Reputation: 16502

How to set bits?

I have a remote service that receives a number of parameters and an integer to flag which ones are null:

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

I've tried a naive implementation but since I've no experience in bit shifting I'd rather not show it.

So, given a vector of booleans, how can I create my bit map?

Upvotes: 2

Views: 349

Answers (1)

Jonas
Jonas

Reputation: 7017

If param_count is known at compile time you can use std::bitset. Here is an example:

// 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());

If param_count is not known at compile time, you can use std::vector<bool>. Here is another example:

// 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; });

The conversion from std::vector<bool> to int is taken from this answer.

Upvotes: 4

Related Questions