我有一个5字节的数据元素,需要在C++中设置其中一个字节的某个位,请参考下面的示例代码:
char m_TxBuf[4];
我希望将字节
m_TxBuf [1]
的第二个位设置为高电平。
00000 0 00 ^ 这个非常感谢您的支持; 谢谢!
我有一个5字节的数据元素,需要在C++中设置其中一个字节的某个位,请参考下面的示例代码:
char m_TxBuf[4];
m_TxBuf [1]
的第二个位设置为高电平。
00000 0 00 ^ 这个非常感谢您的支持; 谢谢!
您可以使用按位或 (|
) 来设置单个位,使用按位与 (&
) 来清除它们。
m_TxBuf[1] |= 4;
要设置一个位,您需要使用按位或运算符。上面的代码使用了复合赋值运算符,这意味着左侧是输入之一,输出结果也是其中之一。
int bitPos = 2; // bit position to set
m_TxBuf[1] |= (1 << bitPos);
通常我们使用位运算符OR(operator |或operator |=作为一种简写)来设置位。
为了简单起见,假设每个字节有8位(其中MSB被认为是'7st'位,LSB被认为是0th位:MSB 0):
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;
}
// If the 5th bit is set...
if (some_char & 1 << 2)
...
只需使用 std::bitset<40>,然后直接索引位。