Arthur Attout
Arthur Attout

Reputation: 2916

Java hexadecimal converter ignores the first digit

I have a character unicode value in decimal (capital A is 65).

When going higher in values, for example 120016 is a mathematical A, I have to retrieve the character based on it's value in decimal.

To achieve that, I used

char c = (char)key;

I encounter a very strange behavior : the first hexadecimal digit is ignored.

Here is a screenshot from NetBeans.

Here is the unicode value of the character I want to print

enter image description here

120016 converted in Hex is 1D4D0. However, when it is converted by the code above, it is converted as \uD4D0, as you can see, the first Hex digit is ignored.

enter image description here

I have absolutely no idea why this is happening. There is no instruction inbetween those two statements, the key value is only given as a parameter, so it cannot have been changed by the time it is converted in hex.

Upvotes: 1

Views: 262

Answers (3)

ControlAltDel
ControlAltDel

Reputation: 35011

Mathematical A is 120016 in utf-8 Java uses utf-16 , so that is why you're seeing a different value- it is different encoding

Upvotes: 1

holi-java
holi-java

Reputation: 30686

a int spend 32 bits, a char spend 16 bits and a hex digit spend 4 bits. when cast a int to a char, the bits that overflowed will be truncated. for example:

int key = 0b00000000000000011101010011010000;//120016
                            ^---------------
char c  =                 0b1101010011010000;// (c = (char)key) == 0xD4D0

Upvotes: 0

davidxxx
davidxxx

Reputation: 131346

As Thorbjørn Ravn Andersen explained, casting an int to a char silently discards bytes consumed by an int (4 bytes) that exceeds the limits of the char type(2 bytes).

To bypass this limitation, don't make the conversion to a char but to a String.
You can use the Integer.toHexString(int) method that returns a string representation of the integer argument as an unsigned integer in base 16.

int x =  120016;
String string = Integer.toHexString(x);

Upvotes: 0

Related Questions