[英]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
的轉換是從此答案獲取的 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.