Bitwise Operations in Java

To create a byte variable in Java try this example:

byte b = (byte) 16;
b = b >> 2;
 

The result of “b” would be 4.

Explanation:

Note that it will be stored in a 32 bit format. so 16 would be:

00000000 00000000 00000000 00010000

Then we shift 2 bits to the left, so the answer would be:

00000000 00000000 00000000 00000100

Thus, we got the decimal value of 4.

Here are the bitwise operations supported by Java

~       Unary bitwise complement ( inverse )
<<      Signed left shift
>>      Signed right shift
>>>     Unsigned right shift
&       Bitwise AND
^       Bitwise exclusive OR ( 1 OR 1 is counted as 0, the rest of the combinations is the same as inclusive OR )
|       Bitwise inclusive OR

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s