This week's book giveaway is in the Security forum.We're giving away four copies of Penetration Testing Basics and have Ric Messier on-line!See this thread for details.
Win a copy of Penetration Testing Basics this week in the Security forum!

Guoqiao Sun
Ranch Hand
Posts: 317
In the following code:
<code>
System.out.println(Integer.toHexString((0x81^0x1)));
System.out.println(Integer.toHexString((byte)0x81^0x1));
</code>
The result is:
80
ffffff80
I know in the second case, the byte will be promoted to int before the shift operation. But why it is not promoted to:
0x00000081 but to 0xffffff81.
Guoqiao

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
The bit pattern of 0x81^0x1 is:
1000 0000
which is a negative number when converted to an int.

Anonymous
Ranch Hand
Posts: 18944
In other words, the bit pattern of 0x81^0x1 is calculated as follows:
0x81 ==> 10000001
0x1 ==> 00000001
=================
10000000
Because the resultant bit pattern above is signed (the "1" in the first bit causes it to be negative), when promoted to an int this negative sign is passed on.

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
Remember, the largest positive number that can be stored in a byte is:
0111 1111
which is 127.

Guoqiao Sun
Ranch Hand
Posts: 317
Thank you all. Can I understand it in this way:
For <code>0x81^0x1</code>, internally it is denoted as:

but for <code>(byte)0x81^0x1</code>, it will be promoted to:

Thanks again.
Guoqiao
Originally posted by Erik Gfesser:
In other words, the bit pattern of 0x81^0x1 is calculated as follows:
0x81 ==> 10000001
0x1 ==> 00000001
=================
10000000
Because the resultant bit pattern above is signed (the "1" in the first bit causes it to be negative), when promoted to an int this negative sign is passed on.