Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a string as hexadecimal bytes

I have this string: Hello, World! and I want to print it using Python as '48:65:6c:6c:6f:2c:20:57:6f:72:6c:64:21'.

hex() works only for integers.

How can it be done?

like image 801
Eduard Florinescu Avatar asked Aug 31 '12 11:08

Eduard Florinescu


People also ask

How do you print a hex value of a string in Python?

hex() function in Python hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

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 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.


3 Answers

You can transform your string to an integer generator. Apply hexadecimal formatting for each element and intercalate with a separator:

>>> s = "Hello, World!"
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:2c:20:57:6f:72:6c:64:21
like image 195
Fedor Gogolev Avatar answered Oct 17 '22 00:10

Fedor Gogolev


':'.join(x.encode('hex') for x in 'Hello, World!')
like image 159
Aesthete Avatar answered Oct 16 '22 23:10

Aesthete


For Python 2.x:

':'.join(x.encode('hex') for x in 'Hello, World!')

The code above will not work with Python 3.x. For 3.x, the code below will work:

':'.join(hex(ord(x))[2:] for x in 'Hello, World!')
like image 57
Kelvin Hu Avatar answered Oct 16 '22 22:10

Kelvin Hu