Convert hex string to byte []

后端 未结 2 1909
旧时难觅i
旧时难觅i 2020-12-10 14:30

I\'ve got a String like this:

init_thread = \"2b11020000ed\"

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

         


        
2条回答
  •  离开以前
    2020-12-10 15:00

    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;
    }
    

提交回复
热议问题