JAVA: get Hex values ​​from UTF-8 from a string?

I would like to be able to convert a raw UTF-8 string to a hexadecimal string. In the example below, I created a sample UTF-8 string containing 2 letters. Then I try to get Hex values, but it gives negative values.

How can I get him to give me 05D0 and 05D1

String a = "\u05D0\u05D1";
byte[] xxx = a.getBytes("UTF-8");

for (byte x : xxx) {
   System.out.println(Integer.toHexString(x));
}

Thank.

+5
source share
2 answers

Do not convert to an encoding such as UTF-8 if you want a code point. Use Character.codePointAt .

For instance:

Character.codePointAt("\u05D0\u05D1", 0) // returns 1488, or 0x5d0
+5
source

, byte -128 127. :

String a = "\u05D0\u05D1";
byte[] xxx = a.getBytes("UTF-8");

for (byte x : xxx) {
    System.out.println(Integer.toHexString(x & 0xFF));
}

, x & 0xFF x, byte int, .

+3

All Articles