Re: Setting bits to on and off
4600cc wrote:
Hi. This might sound dumb, but I need some guidence. I need to know how to
set bits to 1 and to 0, on and off. Thus far I can set a single bit to 1 by
using LSH and bitwise OR operators, but can't figure out how to set a single
bit to 0. Please give me some ideas on how to turn on and off bits. Thank
you.
(Note: Example code below stresses clarity over efficiency. For best
results, use std::bitset when possible.)
The following tautologies may help you. If b is a single bit, then:
(1a) b | 1 == 1
(1b) b | 0 == b
(2a) b & 1 == b
(2b) b & 0 == 0
(3a) b ^ 1 == ~b
(3b) b ^ 0 == b
(Note: & means AND, | means OR, ^ means XOR.)
There are two steps to manipulating a bit within a number. First,
define a "mask". Second, apply that mask to your number using some
bitwise operation.
The tasks we are usually interested in are: setting a bit, unsetting a
bit, flipping a bit, testing the value of a bit.
Setting a bit:
We will use bitwise OR (|) to accomplish this task. (1a) tells us that
the bit(s) we would like set to 1 should have a 1 in the corresponding
position in our mask. (1b) tells us that placing a 0 in each of the
mask's other bit positions will leave the original bit unchanged.
Example:
unsigned set(unsigned x, unsigned n)
{
unsigned mask = 1 << n ;
return (x | mask) ;
}
Unsetting a bit:
We will use bitwise AND (&) to accomplish this task. (2b) tells us that
the bit(s) we would like unset should have a 0 in the corresponding
position in our mask. (2a) tells us that placing a 1 in each of the
mask's other bit positions will leave the original bit unchanged. Note
the mask required to unset a bit is the bitwise NOT(~) of the mask
required to set a bit.
Example:
unsigned unset(unsigned x, unsigned n)
{
unsigned mask = ~(1 << n) ;
return (x & mask) ;
}
Flipping a bit:
We will use bitwise XOR (^) to accomplish this task. (3a) tells us that
the bit(s) we would like flipped should have a 1 in the corresponding
position in our mask. (3b) tells us that placing a 0 in each of the
mask's other bit positions will leave the original bit unchanged.
Example:
unsigned flip(unsigned x, unsigned n)
{
unsigned mask = 1 << n ;
return (x ^ mask) ;
}
Testing the value of a bit:
We will use bitwise AND (&) to accomplish this task. We will place a 1
in the mask in the position we wish to check, and 0 in the remaining
positions. Note that by (2b), all positions in which we are not
interested will be forced to 0. By (2a), the position we are interested
in will remain unchanged. Therefore, if the bit is not set, the result
will be all 0s.
Example:
bool is_set(unsigned x, unsigned n)
{
unsigned mask = 1 << n ;
return (x & mask) ? true : false ;
}
--
Alan Johnson