【问题标题】:boost dynamic_bitset copy bits from uint16从 uint16 提升 dynamic_bitset 复制位
【发布时间】:2015-11-03 15:49:03
【问题描述】:

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

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

我的代码我试过但错了:

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

【问题讨论】:

    标签: c++ boost boost-dynamic-bitset


    【解决方案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
    

    【讨论】:

    • 感谢指正。但是这段代码会将bitset中int值的第0位替换为布尔值。
    • 重新阅读编辑后的问题后更新。 Live on Coliru
    【解决方案2】:

    所以,我设法以这种方式做到了,没有 boost 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;
    

    【讨论】:

    • true &lt;&lt; 0 - 这是为了达到什么目的
    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2017-01-14
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    相关资源
    最近更新 更多