Monday 26 November 2012

Puzzle 6: Multicast

int i = -1;
byte b = (byte)i;
char c = (char)b;
int i2 = (int)c;

The value of the variable in binary format is:

i = 1111 1111 1111 1111 1111 1111 1111 1111
b = 1111 1111
c = 1111 1111 1111 1111
i2 = 0000 0000 0000 0000 1111 1111 1111 1111

So we can see, from char to int, the sign is not considered. Simply prefixing 0s will do it.

If you wish to keep the sign, you need to cast char to short

short s = (short)c;
int i3 = (int)s;

result is:

s = 1111 1111 1111 1111
i3 = 1111 1111 1111 1111 1111 1111 1111 1111

If you cast byte to char, and you don't want to keep the sign. e.g. you want to achieve the following effect.

b = 1111 1111
c = 0000 0000 1111 1111

You can use bit mask:

char c = (char)(b & 0xff);

b & 0xff is of type int, so effectively

b & 0xff = 0000 0000 0000 0000 0000 0000 1111 1111

No comments:

Post a Comment