Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About primitive promotion.

 
Guoqiao Sun
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Please tell, thanks in advance.
Guoqiao
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The bit pattern of 0x81^0x1 is:
1000 0000
which is a negative number when converted to an int.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember, the largest positive number that can be stored in a byte is:
0111 1111
which is 127.
 
Guoqiao Sun
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic