This week's book giveaway is in the OCAJP 8 forum.We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!

Guoqiao Sun
Ranch Hand

Joined: Jul 18, 2001
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

Guoqiao Sun<br />SCJP2 SCWCD2<br />Creator of <a href="http://www.jiris.com/" target="_blank" rel="nofollow">www.jiris.com</a>, Java resource, mock exam, forum
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
The bit pattern of 0x81^0x1 is:
1000 0000
which is a negative number when converted to an int.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Anonymous
Ranch Hand

Joined: Nov 22, 2008
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

Joined: May 05, 2000
Posts: 13974
Remember, the largest positive number that can be stored in a byte is:
0111 1111
which is 127.
Guoqiao Sun
Ranch Hand

Joined: Jul 18, 2001
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.

I agree. Here's the link: http://aspose.com/file-tools