Search code examples
javahexdecode

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

  • Try the following:

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