Forums Register Login

About primitive promotion.

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
The bit pattern of 0x81^0x1 is:
1000 0000
which is a negative number when converted to an int.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Remember, the largest positive number that can be stored in a byte is:
0111 1111
which is 127.
+Pie Number of slices to send: Send
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.


My favorite is a chocolate cupcake with white frosting and tiny ad sprinkles.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 682 times.
Similar Threads
shifting
S.o.p (byte) 0X81 >> 2
byte 0x7f, 0x80, 0x81
bit shift
byte to integer conversion -- mock exam qtn
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 18:28:01.