Bitwise Operators in Java
Bitwise Logical Operators
- & (bitwise AND)
- | (bitwise OR)
- ~ (bitwise NOT)
- ^ (bitwise XOR)
Bitwise Shit Operators
- << (bitwise left shift)
- >> (bitwise right shift)
- >>> (bitwise unsigned right shift)
- &= (bitwise AND assignment)
- |= (bitwise OR assignment)
- ^= (bitwise XOR assignment)
- <<= (bitwise left shift and assignment)
- >>= (bitwise right shift and assignment)
- >>>= (bitwise unsigned right shift and assignment)
int a = 2; //0010
int b = 4; //0100
int c=a&b; // the result is zero
- Smaller types like byte, short are promoted to int before applying bit shift operator in Java. This requires explicit casting on lower type of result.
- If number of shift positions exceeds with number of bits in a variable, then remainder operator is used to calculate effective bit movement. For example int variables contains 32 bit, and if you shift bits to 33 times, then its equivalent of shifting bits 33%32 or just 1 time. e.g. 8 >> 33 is equal to 8 >> 1 and this is true for all bit shift operators.
- Since bit shift operators can simulate divide by 2 and multiplied by 2 operation they can be used to implement fast multiplication and division but on the cost of readability as its difficult to comprehend code written using bit shift operators in Java.
No comments:
Post a Comment