Java Quick Guide

 
 
This guide contains useful Java information.

rss feed






Java bitwise operations.



Information
nibble = 4 bits
byte = 8 bits
word = 2 bytes = 16 bits
dword = 2 words = 4 bytes = 32 bits


Nibble Hex value
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F



Bitwise operators Description
& AND

1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0
| OR

1 | 1 == 1
1 | 0 == 1
0 | 1 == 1
0 | 0 == 0
^ XOR

1 ^ 1 == 0
1 ^ 0 == 1
0 ^ 1 == 1
0 ^ 0 == 0
~ Ones complement, inversion operator

~0 == 1
~1 == 0
~00110010 == 11001101
<< Left shift

Shifts x to the left by y bits. The high order bits are lost while zeros fill the right bits.

x << y

For example:
11101101 << 2 == 10110100

byte val = (byte)0xed;
byte val_shift = (byte)(val<<2);

String a = Integer.toBinaryString(256 + (int) val);
System.out.println(a.substring(a.length() -8));

String b = Integer.toBinaryString(256 + (int) val_shift);
System.out.println(b.substring(b.length() -8));
>> Right shift signed

The low order bits are lost while the sign bit value (0 for positive numbers, 1 for negative) fills in the left bits.

x >> y

For example:
11101101 >> 2 == 11111011

byte val = (byte)0xed;
byte val_shift = (byte)(val>>2);

String a = Integer.toBinaryString(256 + (int) val);
System.out.println(a.substring(a.length() -8));

String b = Integer.toBinaryString(256 + (int) val_shift);
System.out.println(b.substring(b.length() -8));
>>> Right shift unsigned

Shifts x to the right by y bits. The low order bits are lost while zeros fill in the left bits regardless of the sign. This operator ONLY works for 32- and 64-bit values.

x >>> y

For example:
11111111 11111111 11111111 11111111 >>> 24 ==
00000000 00000000 00000000 00000000

int a = -1;
a = a >>> 24;
System.out.println(a);