masmic
masmic

Reputation: 3564

Convert hex string to byte []

I've got a String like this:

init_thread = "2b11020000ed"

I have to send this string via bluetooth, for what I do this:

byte[] init = init_thread.getBytes();
GlobalVar.mTransmission.write(init);

What I need is to define that the init_thread string is an hex string before converting it to bytes, because if I do this way, it is getting it wrong:

What is doing now = 2(1byte), b(1byte), 1(1byte), 1(1byte)...

What must do = 2b(1byte), 11(1byte), 02(1byte)...

Upvotes: 13

Views: 34614

Answers (2)

Ijas Ahamed N
Ijas Ahamed N

Reputation: 6110

If we want to convert hex to byte array, we should make sure that hex string length should be of even length. Below method handles this

public static byte[] hexToByteArray(String hex) {
    hex = hex.length()%2 != 0?"0"+hex:hex;

    byte[] b = new byte[hex.length() / 2];

    for (int i = 0; i < b.length; i++) {
        int index = i * 2;
        int v = Integer.parseInt(hex.substring(index, index + 2), 16);
        b[i] = (byte) v;
    }
    return b;
}

Upvotes: 1

getKonstantin
getKonstantin

Reputation: 1250

Convert hex to byte and byte to hex.

public static byte[] hexStringToByteArray(String s) {
                int len = s.length();
                byte[] data = new byte[len/2];

                for(int i = 0; i < len; i+=2){
                    data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
                }

                return data;
            }

final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String byteArrayToHexString(byte[] bytes) {
            char[] hexChars = new char[bytes.length*2];
            int v;

            for(int j=0; j < bytes.length; j++) {
                v = bytes[j] & 0xFF;
                hexChars[j*2] = hexArray[v>>>4];
                hexChars[j*2 + 1] = hexArray[v & 0x0F];
            }

            return new String(hexChars);
        }

Upvotes: 38

Related Questions