I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - "05", 16 - "10", etc.
Example:
Input: [0,1,2,3,127,200,255], Output: 000102037fc8ff
I've managed to come up with:
#!/usr/bin/env python def format_me(nums): result = "" for i in nums: if i <= 9: result += "0%x" % i else: result += "%x" % i return result print format_me([0,1,2,3,127,200,255])
However, this looks a bit awkward. Is there a simpler way?
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.
The format for coding a hexadecimal string constant is: X'yy...yy' The value yy represents any pair of hexadecimal digits. You can specify up to 256 pairs of hexadecimal digits.
To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.
The 02x tells Python we want the number represented as a 2 digit hexadecimal number, where any missing digits are padded with zeroes. You can find an exhaustive list of formatting options in the Python documentation l linked earlier.
Just for completeness, using the modern .format()
syntax:
>>> numbers = [1, 15, 255] >>> ''.join('{:02X}'.format(a) for a in numbers) '010FFF'
''.join('%02x'%i for i in input)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With