簡體   English   中英

如何設置位?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM