Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
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?
Posted

You need to OR those bits together: http://en.wikipedia.org/wiki/Operators_in_C_and_C++#Bitwise_operators[^].

For example 1 | (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:
C++
existingBitSet |= bitsToSet;


For clearing bits, first OR them together (obtain bitsToClear, see below) and than use the operators '& ('&=') and ~ (not):
C++
existingBitSet &= ~bitsToClear;


See also: http://en.wikipedia.org/wiki/Bit_manipulation[^].

—SA
 
Share this answer
 
v3
Quote:
num|(1<<n)
Actually you use
C
num |= (1 << n);

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
C
num |= 0xFF;

sets the bits 0..7 of num

while
C
num &= ~0xFF;

clears the same bits.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900