Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create python bytes object from long hex string?

Tags:

python

hex

byte

I have a long sequence of hex digits in a string, such as

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?

like image 557
recursive Avatar asked Jan 14 '09 17:01

recursive


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.

How do you create a byte object in Python?

The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.

How do you convert bytes to hex in Python?

Use the hex() Method to Convert a Byte to Hex in Python The hex() method introduced from Python 3.5 converts it into a hexadecimal string. In this case, the argument will be of a byte data type to be converted into hex.


2 Answers

Works in Python 2.7 and higher including python3:

result = bytearray.fromhex('deadbeef') 

Note: There seems to be a bug with the bytearray.fromhex() function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown:

>>> bytearray.fromhex('B9 01EF') Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be unicode, not str` 
like image 79
Jim Garrison Avatar answered Oct 06 '22 01:10

Jim Garrison


result = bytes.fromhex(some_hex_string) 
like image 39
vili Avatar answered Oct 05 '22 23:10

vili