triple type casting bit work - widening from char to long

0

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: 0xfffffffe

I know that the output is fffe but why (O_o)?

Thanks in advance.

java
types
casting
asked on Stack Overflow Jun 18, 2015 by jank • edited Jun 18, 2015 by Andy Korneyev

1 Answer

-1

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);

Output:

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.)

What happens?

-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.

answered on Stack Overflow Jun 18, 2015 by Uwe Schmidt • edited Jun 18, 2015 by Uwe Schmidt

User contributions licensed under CC BY-SA 3.0