I'm trying to figure out the bit casting in the line below:
long a = (long) (int) (char) (-2)
I want to represent it as an hex number
what comes before what?
i've tried to cast from right to left so i just padded with 1's and the result is:
I know that the output is fffe but why (O_o)?
Thanks in advance.
Thats my example-code:
// equal to question long a = (long) ((int) ((char) (-2))); //printing partial solutions int number = -2; char c = (char)number; int i = (int)c; long l = (long)i; System.out.printf("number: %08x\n", number); System.out.printf("char: %08x\n", (int)c); //cast to print System.out.printf("int: %08x\n", i); System.out.printf("long: %08x\n", l);
number: fffffffe char: 0000fffe int: 0000fffe long: 0000fffe
An int has 4 Byte, a char has 2 Byte and a long has 8 Byte.
Every 0.5 Bytes are one hexnumber [0 to f] == [0 to 15]. (2 hex-numbers are 1 Byte.)
A cast don't convert a number from one range to an other. It cuts of the Byte (bit) from the given value to the range from the new value. (If you're cast from a biger range to a smaler.)
-2 is per default an int. You're cast to char (from 4 Byte to 2 Byte). The fist 2 Byte will cut of. So You're result is 0xfffe. Than you're casting to bigger ranges and zeros are add. (Nothing will change.)
So, that's the reason why -2 will be 0xfffe (as number: 65534) after the three casts.
User contributions licensed under CC BY-SA 3.0