Convert hex string to byte []

后端 未结 2 1912
旧时难觅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:08

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

提交回复
热议问题