2

我需要创建 24 位集。第一个 (0) 位必须由 bool 设置。和其他(1 - 23)我需要从 uint32 值复制第一位

是否可以使用 dynamic_bitset 做到这一点?

我尝试过但错误的代码:

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

2 回答 2

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
于 2015-11-03T16:09:23.953 回答
0

所以,我设法以这种方式做到了,没有提升位集:

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;
于 2015-11-04T08:16:38.337 回答