How can I access a specific group of bits from a variable?

前端 未结 4 1013
梦谈多话
梦谈多话 2021-02-06 06:58

I have a variable with \"x\" number of bits. How can I extract a specific group of bits and then work on them in C?

4条回答
  •  孤独总比滥情好
    2021-02-06 07:58

    If you're dealing with a primitive then just use bitwise operations:

    int bits = 0x0030;
    bool third_bit = bits & 0x0004;  // bits & 00000100
    bool fifth_bit = bits & 0x0010;  // bits & 00010000
    

    If x can be larger than a trivial primitive but is known at compile-time then you can use std::bitset<> for the task:

    #include
    #include
    
    // ...
    std::bitset<512> b(std::string("001"));
    b.set(2, true);
    std::cout << b[1] << ' ' << b[2] << '\n';
    
    std::bitset<32>  bul(0x0010ul);
    

    If x is not known at compile-time then you can use std::vector and then use bit-manipulation at runtime. It's more work, the intent reads less obvious than with std::bitset and it's slower, but that's arguably your best option for x varying at runtime.

    #include
    
    // ...
    std::vector v(256);
    v[2] = 1;
    bool eighteenth_bit = v[2] & 0x02;  // second bit of third byte
    

提交回复
热议问题