Converting hexstring to byte array in java and python

Here is sample code that I tried for conversion in java and python. I am new to this concept. Why am I getting different value? How can I get the same value that I got in java in python?

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;
    }
output :[B@57829d67
In python I tried:
test = bytearray.fromhex("4BE7C580")
output : bytearray(b'K\xe7\xc5\x80')

1 answer

  • answered 2018-01-11 20:52 Roger Lindsjö

    Seems correct.

    public static void main(String[] args) {
        byte[] array = hexStringToByteArray("4BE7C580");
        System.err.println(Arrays.toString(array));
        for (byte b : array) {
            System.err.println(Integer.toHexString(b & 0xff));
        }
    }
    
    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;
    }
    

    gives

    [75, -25, -59, -128]
    4b
    e7
    c5
    80