umirza47
umirza47

Reputation: 940

Java - Bitwise comparisons and shifting of bits

I need a little explanation of the following statement, What is it doing?:

int result = 154 + (153 << 8) + (25 << 16) + (64 << 24);
/* what would be the value of result after this line and how it is calculated
Why we need this? */

Upvotes: 1

Views: 212

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213371

(153 << 8) is equivalent to 153 * pow(2, 8)

You are actually shifting your bits towards left..

Also: -

(153 >> 8) is equivalent to 153 / pow(2, 8)

You can guess why.. This is actually shifting bits towards right..

E.G: -

3 => 0011

3 << 2 is equal to 1100 -> (Which is code for 12)

3 >> 2 is equal to 0000 -> (Which is code for 0) -> you can see - **(3 / 4 = 0)**

NOTE :- Note that the right shifting rounds off towards negative infinity..

For E.G: -

-3 >> 1 --> -2 (-1.5 is rounded to -2)

Lets see how it happens: -

In binary string representation: -

-3 ==> 11111111111111111111111111111101

-3 >> 1 ==> 11111111111111111111111111111110 (-3 / 2 = -1.5 -> rounded to -2)

(Note the left most bit is filled by the bit that was present at the left most end before shift (1 in this case))

So, the value becomes, -2 (for -3>>1, which is greater than -3) This happens for negative numbers.. Right shifting a negative number gives a number greater than the original number..

Which is contrary to the positive number where the left most bit will be filled by 0... Thus value obtained will be less than the original..

3 ==>  00000000000000000000000000000011

3 >> 1 ==> 00000000000000000000000000000001 (3 / 2 = 1.5 -> rounded to 1)

(So left most bit remains 0. So, the value is 1 (less than 3), i.e., value is rounded off towards negative infinity and becomes 1 from 1.5)

Similarly you can devise results for left-shifting positive and negative number..

Upvotes: 4

Matthew Kirkley
Matthew Kirkley

Reputation: 4208

The answer is 1075419546. The left shift operator is basically addings 0s to the binary representations of the decimal numbers so this would simply to

154 + 153 * 2^8 + 25 * 2^16 + 64*2^24

So you can convert 153 to its binary representation, then add 8 zeros and convert back to decimal etc etc..

Upvotes: 2

in practical terms, if you use the given operator on a math expression it has the same meaning as the following:

123 << n is exactly the same as 123 * 2 ^ n

For example, 2 << 2 is 2 * 2 ^ 2 which is 8 or the same as 1000

Otherwise, you are just shifting bits to the left:

3 = 11 then 3 << 2 = 1100.

Hope it makes it clear.

Upvotes: 0

Related Questions