Bit Operators
~ | bitwise NOT | ~expr |
<<, >> | left/right shift | expr1 << expr2 |
& | bitwise AND | expr1 & expr2 |
^ | bitwise XOR | expr1 ^ expr2 |
| | bitwise OR | expr1 | expr2 |
1. listed by their precedence
2. bitwise operators take operands of integral type
3. the sign bit is handled machine-dependent, so we'd better use unsigned type when using integral value with the bitwise operatorsNOT operator (~) is similar in behavior to the bitset flip operation:
unsigned char bits = 0227; //10010111
bits = ~ bits; //01101000
Shift operator(<<, >>) will discard the bits that are shifted off the end. (The right-hand operand must not be negative and must be a value that is strictly less than the number of bits in the left-hand operand)
unsigned char bits = 0233; //10011011
bits <<1; //00110110 the left most bit is discarded
And operator(&) will return 1 when
both operands are 1; or 0.
XOR operator(^) will return 1 if either but not both operands contain 1 ; or 0.
OR operator(|) will return 1 if either or both operands are 1; or 0.
Bitset library are more direct easier than manipulate integral with bitwise operation.
Shift Operators has midlevel precedence:lower than arithmetic operators, but higher than relational, assignment, or conditional operators:
cout << 42 + 10; //ok, + has higher precedence
cout << (10 < 42); //ok, parentheses force intended grouping, result is 1
cout << 10 < 42; //error, attempt to compare cout to 42
Mask
In computer science, a mask is data that is used for bitwise operations, particularly in a bit field.
Using a mask, multiple bits in a byte, nibble, word (etc.) can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation.
Common Masking functions
Masking bit to 1
Y | 1 = 1
Masking bit to 0
Y & 0 = 0
Query Status of a bit
Turn off all other bits:
10011101 10010101
AND 00001000 00001000
= 00001000 00000000
Toggling bit values
Y ^ 0 = Y
Y ^ 1 = ~Y
// Example:
10011101 10010101
XOR 00001111 11111111
= 10010010 01101010
Bit Facts and Tricks
x ^ 0s = x | x & 0s = 0 | x | 0s = x |
x ^ 1s = ~x | x & 1s = x | x | 1s = 1s |
x ^ x = 0 | x & x = x | x | x = x |
Common Bit Tasks
Get Bit
Get certain bit in a int value num:
boolean getBit(int num, int i)
{
return ( (num & (1 << i))!=0 );
}
Set Bit
set certain bit:
int setBit(int num, int i)
{
return num | (1 << i);
}
Clear Bit
clear ith bit:
int clearBit(int num, int i)
{
int mask = ~(1 << i);
return num & mask;
}
clear all bits from most significant bit through i(inclusive)
int clearBitsMSBthroughI(int num, int i)
{
int mask = (1 << i) - 1;
return num & mask;
}
clear all bits from i to 0(inclusive)
int clearBitsIthrough0(int num, int i)
{
int mask = ~((1 << (i+1)) - 1);
return num & mask;
}
Update Bit
// update the ith bit to value v (v is 0 or 1)
int updateBit (int num, int i, int v)
{
int mask = ~(1 << i);
return (num & mask) | (v << i);
}
Decimal to Binary translate
http://www.wikihow.com/Convert-from-Decimal-to-Binary