Subject: Here are the outputs
Author: EricJ
In response to: Java Data Type Conversions and Promotions
Posted on: 08/31/2007 06:58:29 PM
(int)0x81 = 129
129&0xFF --> 129
129&0xFFFFFFFF --> 129
(byte)0x81 = -127
-127&0xFF --> 129
-127&0xFFFFFFFF --> -127
(int)((byte)0x81) --> 0xffffff81
(int)((byte)0x81) = -127
-127&0xFF --> 129
-127&0xFFFFFFFF --> -127
So, be very careful while handling data of byte, particularly byte-int conversion.
For example,
(byte)0x81 != (int)0x81
(int)((byte)0x81) != 0x81
But
((byte)0x81)&0xFF == ((int)0x81)&0xFF
>
> On 08/31/2007 06:56:54 PM
EricJ wrote:
/**
* testing for byte-int conversion
* what is intended to demonstrate is:
* (int)((byte)0x81) != (int)0x81
*/
public class test{
public static void main(String[] args)
{
// indentity conversion(int->int):
// 0x00000081 --> j1=129 ( two's complement value)
int j1 = 0x81;
System.out.println();
System.out.println("(int)0x81 = " + Integer.toString(j1)); // (int)0x81 = 129
System.out.println(j1 + "&0xFF --> " + Integer.toString(j1&0xFF)); // 129&0xFF --> 129
System.out.println(j1 + "&0xFFFFFFFF --> " + Integer.toString(j1&0xFFFFFFFF)); // 129&0xFFFFFFFF --> 129
// narrowing conversion(int->byte):
// 0x00000081(129) -> 10000001(-127) --> b1=-127 ( two's complement value)
// where the sign of 0x00000081 gets lost!
byte b1 = (byte)0x81;
System.out.println();
System.out.println("(byte)0x81 = " + Integer.toString(b1)); // (byte)0x81 = -127
System.out.println(b1 + "&0xFF --> " + Integer.toString(b1&0xFF)); // -127&0xFF --> 129
System.out.println(b1 + "&0xFFFFFFFF --> " + Integer.toString(b1&0xFFFFFFFF)); // -127&0xFFFFFFFF --> -127
// widening conversion(byte->int):
// 10000001(-127) -> 0xffffff81(-127)
// where the sign and magnitude get both perserved
int j2 = b1;
System.out.println();
System.out.println("(int)((byte)0x81) --> 0x" + Integer.toHexString(j2)); // (int)((byte)0x81) --> 0xffffff81
System.out.println("(int)((byte)0x81) = " + Integer.toString(j2)); // (int)((byte)0x81) = -127
System.out.println(j2 + "&0xFF --> " + Integer.toString(j2&0xFF)); // -127&0xFF --> 129
System.out.println(j2 + "&0xFFFFFFFF --> " + Integer.toString(j2&0xFFFFFFFF)); // -127&0xFFFFFFFF --> -127
String comment = "So, be very careful while handling data of byte, " +
"particularly byte-int conversion. For example, \n" +
" (byte)0x81 != (int)0x81 \n" +
" (int)((byte)0x81) != 0x81 \n" +
" but \n" +
" ((byte)0x81)&0xFF == ((int)0x81)&0xFF";
System.out.println();
System.out.println(comment);
}
}
References: