Set individual bit in C++

2020-03-24 06:41发布

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:

char m_TxBuf[4]; 

I would like to set bit 2 to high of byte m_TxBuf[1].

    
00000 0 00
      ^ This one

Any support is greatly appreciated; Thanks!

6条回答
聊天终结者
2楼-- · 2020-03-24 06:57

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.

查看更多
爷的心禁止访问
3楼-- · 2020-03-24 07:03
m_TxBuf[1] |= 4;

To set a bit, you use bitwise or. The above uses compound assignment, which means the left side is one of the inputs and the output.

查看更多
聊天终结者
4楼-- · 2020-03-24 07:04

Bitwise operators in C++.

"...set bit 2..."

Bit endianness.

I would like to set bit 2 to high of byte m_TxBuf[1];

m_TxBuf[1] |= 1 << 2

查看更多
\"骚年 ilove
5楼-- · 2020-03-24 07:05
int bitPos = 2;  // bit position to set
m_TxBuf[1] |= (1 << bitPos);
查看更多
不美不萌又怎样
6楼-- · 2020-03-24 07:06

Just use std::bitset<40> and then index bits directly.

查看更多
不美不萌又怎样
7楼-- · 2020-03-24 07:17

You can use bitwise-or (|) to set individual bits, and bitwise-and (&) to clear them.

查看更多
登录 后发表回答