Java Quick Guide

 
 
This guide contains useful Java information.







Java bitwise operations.



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


NibbleHex value
00000
00011
00102
00113
01004
01015
01106
01117
10008
10019
1010A
1011B
1100C
1101D
1110E
1111F


Bitwise operatorsDescription
& 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);