Bitwise and Bit Shift

Java Bitwise and Bit Shift Operators

Operator Description
| Bitwise OR
& Bitwise AND
~ Bitwise Complement
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift

example

1

System.out.printf("%d*%d=%d", 2,8,2<<3);

2

System.out.printf("%d/2=%d",11,11>>1);

3

public static boolean isOddNum(int n) {
    return (n & 1)==1;
}

4

public static int powerofTwo(int n) {
    return 2<<(n-1);
}	

5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* how to multiply two arbitrary integers a and b (a greater than b)
* using only bitshifts and addition
* @param a
* @param b
* @return
*/
public static int multiply(int a, int b) {
int c = 0;
while (b!=0) {
if ((b & 1)!=0)
c+=a;
a <<= 1;
b >>= 1;
}
return c;
}

6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* how to calculate a sum of two integers a and b
* using bitwise operators and zero-testing
* @param a
* @param b
* @return
*/
public static int sum(int a, int b) {
int c=0;
while(a!=0) {
c = b & a;
b = b ^ a;
c <<= 1;
a = c;
}
return b;
}

JavaScript Bitwise Operators

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
&#124; OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shifts left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
>>> Zero fill right shift Shifts right by pushing zeros in from the left, and let the rightmost bits fall off

ref