Java left shift clarification

sshekhar :

I am unable to figure out the reason for this behavior. I want to left shift by 8 bits the byte value OxAB. Then I want to convert that to a long.

byte oneByte = (byte) 0xAB;
long converted = (oneByte & 0xFF) << 8;
System.out.println(converted);

In this case the output is 43776. However, if I change the code to this:

byte oneByte = (byte) 0xAB;
long converted = (oneByte) << 8;
System.out.println(converted);

The output changes to -21760. I have following questions:

  1. What is the data type of 0xFF?
  2. Why is bitwise AND with 0xFF preventing sign extension?
pero_hero :
long converted = onebyte; // gives you -85

and if you shift it 8 times to the left it gives you exactly -21760 because during the conversion to long the left most bit is used as a sign bit.

long converted = onebyte & 0xFF; //gives you 171

and if you shift it 8 times to the left it gives you 43776

because when using the bitwise and byte, short and char are converted to an int first and then the bitwise operation is executed.

11111111111111111111111110101011 //byte 0xAB casted to int
00000000000000000000000011111111 //0xFF is an int literal
00000000000000000000000010101011 //bitwise and operation

after the bitwise and with 0xFF the sign bit is removed

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194370&siteId=1