bitwise operators - taoualiw/My-Knowledge-Base GitHub Wiki

Bitwise Operators

Bitwise Operators include <<, >>, &, |, ~, and ^. They operate on numbers (normally), but instead of treating that number as if it were a single value, they treat it as if it were a string of bits, written in twos-complement binary.

A two's complement binary is same as the classical binary representation for positve integers but is slightly different for negative numbers. Negative numbers are represented by performing the two's complement operation on their absolute value. A negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1).

Assume it's a question of using the bitwise operator as soon as you hear restriction about not allowed to use arithmetic operator. By the using bitwise operator, there is a nice trick to to check if a number is power of two or not

public static boolean powerOfTwo(int x) { return (x & (x - 1)) == 0; }

Read more: https://javarevisited.blogspot.com/2015/02/50-programmer-phone-interview-questions-answers.html#ixzz5pv0YyDkI

References

https://wiki.python.org/moin/BitwiseOperators

⚠️ **GitHub.com Fallback** ⚠️