2017-07-04 62 views
2

我有收到一些參數和一個整數,以標誌哪些是無效的遠程服務:如何設置位?

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

我已經嘗試了天真的實現,但因爲我沒有經驗,在比特移位我會而不是顯示它。

因此,給定一個布爾值的矢量,我該如何創建我的位圖?

+1

'std :: vector '是一個位圖。就像'std :: bitset':http://en.cppreference.com/w/cpp/utility/bitset – Jonas

+0

如何將'std :: vector '變成一個整數? – ruipacheco

+0

如果您使用'bitset',則可以使用'to_ulong'方法。矢量實現可能會在引擎蓋下使用bitset,但不一定。 –

回答

4

如果編譯時已知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服用。

+0

@ Rakete1111你是對的,我加了一個'矢量'版本。 – Jonas

+0

param_count在編譯時未知。 – ruipacheco