Implement bytes.fromhex() and struct.unpack() in Python through java

Requirements: The data passed in by the third party contains HEX code stream, which needs to be parsed into the data we need

  1. Via 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. Realize this function through Java
  • First convert this hex string to 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);
    }
  • Convert byte[] into the data we need (here we need floating point numbers)
    // 从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]);
    }

You can get the final result

Guess you like

Origin blog.csdn.net/Beer_xiaocai/article/details/107503216