如何在C中设置/重置多个位 [英] How to set/reset multiple bits in C
问题描述
我知道为了设置一个比特,我们使用num |(1<< n),其中它设置第(n + 1)位。如何一次设置/重置多于1位?
I know that in order to set a bit we use num|(1<<n), where it sets the (n+1)th bit. How can I set/reset more than 1 bit at a time?
推荐答案
您需要将这些位组合在一起:http://en.wikipedia.org/wiki/Operators_in_C_and_C++#Bitwise_operators [ ^ ]。
例如1 | (1 << 1)| (1<<<<<<<<<<<<<<<<< 3)
给你11(设置零,第一和第三位a,其他位是清空的)您还可以将OR('|','| =')任何位设置为先前分配的值:
You need to OR those bits together: http://en.wikipedia.org/wiki/Operators_in_C_and_C++#Bitwise_operators[^].
For example1 | (1<<1) | (1<<3)
gives you 11 (zero, first and third bits a are set, other bits are clear). You can also OR ('|', '|=')any bit set to previously assigned value:
existingBitSet |= bitsToSet;
对于清除位,首先将它们组合在一起(获取 bitsToClear
,见下文)并使用运算符' &安培; ('& =')和〜(不):
For clearing bits, first OR them together (obtain bitsToClear
, see below) and than use the operators '& ('&=') and ~ (not):
existingBitSet &= ~bitsToClear;
另请参阅: http://en.wikipedia.org/wiki/Bit_manipulation [ ^ ]。
num |(1< ;< n)
num|(1<<n)
实际上你使用
Actually you use
num |= (1 << n);
设置 n $ c $> $
n
(例如 num | =(1<< 0);
设置位 0
)。
要设置(清除)多个位,只需或
( AND
)具有适当常量的num。
例如
to set the bit n
of num
(for instance num |= (1 << 0);
sets the bit 0
).
To set (clear) multiple bits you have just to OR
(AND
) the num with the appropriate constant.
For instance
num |= 0xFF;
设置位 0..7
num
而
sets the bits 0..7
of num
while
num &= ~0xFF;
清除相同的位。
这篇关于如何在C中设置/重置多个位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!