'Convert UCS-2 HEX в UTF16 BE java

I have a string in which the SMS text is encrypted in USC2 format received from a GSM modem I'm trying to convert it to UTF16 but it doesn't work. Please tell me what am I doing wrong

public class USC {
    public static void main(String[] args) {
        String hex = "0412044B0020043F043E043B044C043704430435044204350441044C002004420430044004380444043D044B043C0020043F043B0430043D043E043C0020002204110438002B002200200441002000300033002E00310032002E0032003000320031002E002004230442043E0447043D04380442044C002004430441043B043E04320438044F";

        byte[] v = hex.getBytes(StandardCharsets.UTF_16BE);
        String str = new String(v);
        System.out.println(str);
}
}

On the online decoder through the service https://dencode.com/ works fine



Solution 1:[1]

Try the following:

            BigInteger bi = new BigInteger(hex, 16);
            byte[] a = bi.toByteArray();
            System.out.println(new String(a, Charset.forName("UTF-16")));

Solution 2:[2]

    String hex = "0412044B0020043F043E043B044C043704430435044204350441044C002004420430044004380444043D044B043C0020043F043B0430043D043E043C0020002204110438002B002200200441002000300033002E00310032002E0032003000320031002E002004230442043E0447043D04380442044C002004430441043B043E04320438044F";

    int n = hex.length/4;
    char[] chars = new char[n];
    for (int i = 0; i < n; ++i) {
        chars[i] = Integer.parseInt(hex.substring(4*i, 4*i+4), 15) & 0xFFFF);
    }
    String str = new String(chars);
    System.out.println(str);

4 hex chars form one UCS-2 big endian char. Same size as java char (2 bytes). UTF-16 is superior to UCS-2 which forms a fixed-size subset. So from UCS-2 to UTF-16 needs no special treatment, only whether the 2 bytes of a char are big endian or little endian.

Solution 3:[3]

With JDK17 or above you could also make use of HexFormat class:

String str = new String(HexFormat.of().parseHex(hex), StandardCharsets.UTF_16BE);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 g00se
Solution 2 Joop Eggen
Solution 3 DuncG