0 votes
1 view
in Blockchain by (11.8k points)

I was trying to decode hex strings similar to the following format:

0x00000000000000000000000000000000000000000000000bf97e2a21966df7fe

I was able to decode it with the online calculator. The correct decoded number should be 220892037897060743166.

However, when I am trying to decode it with python with the following code, it returns error:

"0x00000000000000000000000000000000000000000000000bf97e2a21966df7fe".decode("hex")

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-32-1cf86ff46cbc> in <module>()

      9 key=keyarr[0]

     10 

---> 11 "0x00000000000000000000000000000000000000000000000bf97e2a21966df7fe".decode("hex")

/usr/local/Cellar/python/2.7.13_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/hex_codec.py in hex_decode(input, errors)

     40     """

     41     assert errors == 'strict'

---> 42     output = binascii.a2b_hex(input)

     43     return (output, len(input))

     44 

TypeError: Non-hexadecimal digit found

Then I removed the 0x in the front of the hex number and tried again:

"00000000000000000000000000000000000000000000000bf97e2a21966df7fe".decode("hex")

Then the output became:

'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b\xf9~*!\x96m\xf7\xfe'

I actually don't understand the output ...

In case you are wondering where do those numbers come from, they are from Ethereum blockchain (ERC20) tokens.

1 Answer

0 votes
by (27.7k points)

Hi, the issue is .decode('hex') means you want to treat the string as a sequence of hex encodings of individual characters.

what you need to do is Call int on it with a base of 16:

int(your_string, base=16)

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...