0

I have a hex string (sA) convert from UTF8 string. When I convert hex string sA to UTF8 string, I can't show it in form UI with build mode (run file .jar) but when I run with run mode or debug mode UTF8 string can show in form UI. I use netbeans IDE 7.3.1. My code below:

public String hexToString(String txtInHex) {
    byte[] txtInByte = new byte[txtInHex.length() / 2];
    int j = 0;
    for (int i = 0; i < txtInHex.length(); i += 2) {
        txtInByte[j++] = Byte.parseByte(txtInHex.substring(i, i + 2), 16);
    }
    return new String(txtInByte);
}

private String asHex(byte[] buf) {
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i) {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

2 Answers 2

1

There are multiple problems with this code.

The valid range for byte values is -128 to 127, or -80 to 7F in hex, and Byte.parseByte enforces this. If your asHex method has to process a character whose second byte is greater than 127 it will produce a string that can't be decoded by toHexString.

The asHex method processes only the second byte of the input characters, so it will work correctly only for the first 256 Unicode characters and produce bogus output for the rest of them.

The toHexString method decodes a string from a byte array assuming some platform-specific default encoding, which will give incorrect results if the data was supposedly encoded in UTF-8 and the default encoding is something else.

Why are you trying to create your own methods for encoding and decoding hex strings instead of using a well known and tested library?

Sign up to request clarification or add additional context in comments.

Comments

0
new String(txtInByte, "UTF-8");

Without the encoding the platform encoding is taken, for instance Windows-1252. The same holds for its inverse: String.getBytes-

String s = "....";
byte[] b = s.getBytes("UTF-8");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.