Ohad
Ohad

Reputation: 1647

getting the binary data represented by the hexadecimal string back in java vs python

I know that in python binascii.unhexlify(initValue) return the binary data represented by the hexadecimal string back.

I am trying to convert binascii.unhexlify(initValue) to java.

I tried the following code lines in java but I am getting different results then the code in python:

 DatatypeConverter.parseHexBinary(value);

I run the following example:

my input - hexadecimal string:

 value = '270000f31d32d1051400000000000000000000000006000000000000000000000000000000000000'

when running in python:

 result = binascii.unhexlify(value)

I am getting:

    result = "'\x00\x00\xf3\x1d2\xd1\x05\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

when running in java:

 byte[] bytes = DatatypeConverter.parseHexBinary(value);

I am getting:

   bytes = [39, 0, 0, -13, 29, 50, -47, 5, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

1.why I am getting different results?

  1. why do I get the output in python with '\' marks?

Upvotes: 1

Views: 785

Answers (1)

chx3
chx3

Reputation: 238

The first hex of your result, "'" is exactly 39 in signed char. In python, you can use built-in function ord("'") to get 39. You can probably get what you want in this python code

value = '270000f31d32d1051400000000000000000000000006000000000000000000000000000000000000'
result = binascii.unhexlify(value)
bytes = [ord(x) for x in result]

You will be getting this unsigned char:

[39, 0, 0, 243, 29, 50, 209, 5, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Upvotes: 2

Related Questions