2015-11-03 34 views
2

我需要創建24位的set。 首先(0)位必須由bool設置。 和其他(1 - 23)我需要從uint32中複製第一位數值boost uint16的dynamic_bitset拷貝位

是否可以使用dynamic_bitset來實現?

我的代碼我試過,但錯了:

typedef boost::dynamic_bitset<unsigned char> DataType; 
DataType bs(24, intValue); 
bs.set(0, booleanValue); 

回答

1

只需左移:

DataType bs(24, intValue); 
    bs <<= 1; 
    bs.set(0, boolValue); 

Live On Coliru

#include <boost/dynamic_bitset.hpp> 
#include <iostream> 
typedef boost::dynamic_bitset<unsigned char> DataType; 

int main() { 
    using namespace std; // for readability on SO 
    cout << hex << showbase; 

    uint32_t intValue = 0x666; 
    cout << "input: " << intValue; 

    DataType bs(24, intValue); 

    cout << "\n#1: " << bs << " " << bs.to_ulong(); 

    bs <<= 1; 
    cout << "\n#2: " << bs << " " << bs.to_ulong(); 

    bs.set(0, true); 

    cout << "\n#3: " << bs << " " << bs.to_ulong(); 
} 

打印:

input: 0x666 
#1: 000000000000011001100110 0x666 
#2: 000000000000110011001100 0xccc 
#3: 000000000000110011001101 0xccd 
+0

感謝糾正。但是這段代碼將用布爾值替換bitset中的int值的第0位。 – user1717140

+0

重新閱讀編輯後的問題後更新。 [Live Coliru](http://coliru.stacked-crooked.com/a/c04ac88b05dd1f33) – sehe

0

所以,我設法做到這一點以這種方式,沒有提升的bitset:

uint32_t buffer(0xAAAAAAAA); 
buffer = buffer << 1; 
buffer |= true << 0; 

unsigned char newRecord[3]; 

newRecord[0] = buffer; 
newRecord[1] = buffer << 8; 
newRecord[2] = buffer << 16; 
+0

'true << 0' - 這是什麼試圖實現 – sehe