Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Blockchain by (12.7k 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 (29.5k points)
edited by

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)

You can even check out the Blockchain Certification Course by Intellipaat to have more knowledge about this topic.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...