Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format ints into string of hex

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?

like image 940
facha Avatar asked Apr 14 '11 10:04

facha


People also ask

How do you convert int to hex 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.

What is hex string format?

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.

How do you create a hex string in Python?

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.

What is 02x in Python?

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.


2 Answers

Just for completeness, using the modern .format() syntax:

>>> numbers = [1, 15, 255] >>> ''.join('{:02X}'.format(a) for a in numbers) '010FFF' 
like image 174
gak Avatar answered Oct 17 '22 17:10

gak


''.join('%02x'%i for i in input) 
like image 40
vartec Avatar answered Oct 17 '22 17:10

vartec