Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a int to char and then back to int - doesn't give same result always

I am trying to get a char from an int value > 0xFFFF. But instead, I always get back the same char value, that when cast to an int, prints the value 65535 (0xFFFF).

I couldn't understand why it is generating symbols for unicode > 0xFFFF.

int hex = 0x10FFFF;
char c = (char)hex;
System.out.println((int)c);

I expected the output to be 0x10FFFF. Instead, the output comes back as 65535.

like image 264
Adon Smith Avatar asked Oct 15 '25 17:10

Adon Smith


1 Answers

This is because, while an int is 4 bytes, a char is only 2 bytes. Thus, you can't represent all values in a char that you can in an int. Using a standard unsigned integer representation, you can only represent the range of values from 0 to 2^16 - 1 == 65535 in a 2-byte value, so if you convert any number outside that range to a 2-byte value and back, you'll lose data.

like image 181
Sam Estep Avatar answered Oct 18 '25 05:10

Sam Estep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!