Hema
Hema

Reputation: 986

How can i revert back hexa value of certain language word to UTF-8

I have converted regional language word to hex value and saved to DB. But How can i decode that hexa value back to regional language word.

Here is my Kannada/Telugu word to Hex value conversion

public String toHex(String b){
    String s="";
    for (int i=0; i<b.length(); ++i) s+=String.format("%04X",b.charAt(i)&0xffff);
    System.out.println("Converted value:::"+s); //0C1C0C3E0C350C3E
    return s;
}

Word i have saved is జావా

Hex value saved in database is 0C1C0C3E0C350C3E

Decoded output am getting is : >5>

Is there any way to decode the hex value back to జావా

Code used to decode is

byte[] bytes = DatatypeConverter.parseHexBinary(itemName);
    String s= new String(bytes, "UTF-8");
    System.out.println("Utf..."+s);

Please help...

Upvotes: 0

Views: 53

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109593

public String fromHex(String b) {
    char[] cs = new char[b.length() / 4];
    for (int i = 0; i < cs.length; ++i) {
        int c = Integer.parseInt(b.substring(4 * i, 4 * i + 4), 16) & 0xFFFF;
        cs[i] = (char) c;
    }
    return new String(cs);
}

This assumes that the conversion did not meddle with negative hex values.

Or exploiting that char is UTF-16BE:

byte[] bytes = DatatypeConverter.parseHexBinary(itemName);
return new String(bytes, StandardCharsets.UTF_16);

Upvotes: 1

Lothar
Lothar

Reputation: 5459

char[] data = hexData.toCharArray();
byte[] bytes = new byte[data.length/2];
for (int i = 0; i < data.length; i += 2) {
    String val = new String(data, i, 2);
    bytes[i/2] = Integer.valueOf(val, 16).byteValue();
}
String text = new String(bytes, "UTF8");

You might add sanity checks, e.g. that the length of the input-array is even, etc.

Upvotes: 0

Related Questions