通过java实现Python中bytes.fromhex()与struct.unpack()

需求:在第三方传入过来的数据中,包含HEX码流,需要将其解析为我们需要的数据

  1. 通过Python
>>> a_bytes = bytes.fromhex('42580000')
>>> print(a_bytes)
b'BX\x00\x00'
>>> noiseM = struct.unpack('!f', bytes.fromhex('42580000')[0]
>>> print("noiseM:", noiseM)
noiseM: 54.0
  1. 通过Java实现这一功能
  • 首先将这一hex字符串转为byte[]
    public static byte[] hexStringToBytes(String hexString) {
    
    
        if (hexString == null || hexString.equals("")) {
    
    
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
    
    
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }
        return d;
    }
    private static byte charToByte(char c) {
    
    
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
  • 在将byte[]转化为我们需要的数据(在这里我们需要浮点数)
    // 从byte数组的index处的连续4个字节获得一个float
    public static float getFloat(byte[] arr, int index) {
    
    
        return Float.intBitsToFloat(getInt(arr, index));
    }
    // 从byte数组的index处的连续4个字节获得一个int
    public static int getInt(byte[] arr, int index) {
    
    
        return 	(0xff000000 	& (arr[index+0] << 24))  |
                (0x00ff0000 	& (arr[index+1] << 16))  |
                (0x0000ff00 	& (arr[index+2] << 8))   |
                (0x000000ff 	&  arr[index+3]);
    }

即可得到最终结果

猜你喜欢

转载自blog.csdn.net/Beer_xiaocai/article/details/107503216