Maryadi Poipo
Maryadi Poipo

Reputation: 1478

wrong result from left shift in java

I have made a variable in java, byte a = 0xA6; //10100110 then I made this :

System.out.println(Integer.toHexString( ((short)a<<8)&0xFFFF ));

The result is 0xA600. This is the right result. But when i tried

System.out.println(Integer.toHexString( ((short)a<<3)&0xFFFF ));

The expected result should be : 0x530 (10100110000) but I got 0xFD30(1111110100110000) Emm... Can somebody explain how I got that wrong result...??

thanks... :-)

Upvotes: 1

Views: 128

Answers (2)

Henry
Henry

Reputation: 43728

The byte value A6 represents a negative number (bytes are signed in Java). When you cast to a short it gets sign extended to FFA6. Moreover the shift operation is executed with integer values so it is again sign extended to FFFFFFA6. Shift left by three bits gives FFFFFD30 and taking the lower 16 bits gives 0000FD30.

This does not matter if you shift by 8 bits because you shift out and mask the additional 1 bits.

Upvotes: 1

Kao
Kao

Reputation: 7364

When you declare initialize byte variable you have to downcast it from integer:

byte a = (byte) 0xA6;

So, instead of 10100110 you've got 11111111111111111111111110100110.

And, beacuse of this left shift works in that way:

 ((short)a<<8)&0xFFFF 

returns 1010011000000000

 ((short)a<<3)&0xFFFF 

returns 1111110100110000

Upvotes: 0

Related Questions