Set individual bit in C++

前端 未结 6 849
深忆病人
深忆病人 2021-01-13 13:33

I have a 5 byte data element and I need some help in figuring out how in C++ to set an individual bit of one of these byte; Please see my sample code below:



        
6条回答
  •  感动是毒
    2021-01-13 14:19

    Typically we set bits using bitwise operator OR (operator| or operator|= as a shorthand).

    Assuming 8-bits to a byte (where the MSB is considered the '7st' bit and the LSB considered the 0th: MSB 0) for simplicity:

    char some_char = 0;
    some_char |= 1 << 0; // set the 7th bit (least significant bit)
    some_char |= 1 << 1; // set the 6th bit
    some_char |= 1 << 2; // set the 5th bit
    // etc.
    

    We can write a simple function:

    void set_bit(char& ch, unsigned int pos)
    {
        ch |= 1 << pos;
    }
    

    We can likewise test bits using operator&.

    // If the 5th bit is set...
    if (some_char & 1 << 2)
        ...
    

    You should also consider std::bitset for this purpose which will make your life easier.

提交回复
热议问题