Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorating Hex function to pad zeros

I wrote this simple function:

def padded_hex(i, l):     given_int = i     given_len = l      hex_result = hex(given_int)[2:] # remove '0x' from beginning of str     num_hex_chars = len(hex_result)     extra_zeros = '0' * (given_len - num_hex_chars) # may not get used..      return ('0x' + hex_result if num_hex_chars == given_len else             '?' * given_len if num_hex_chars > given_len else             '0x' + extra_zeros + hex_result if num_hex_chars < given_len else             None) 

Examples:

padded_hex(42,4) # result '0x002a' hex(15) # result '0xf' padded_hex(15,1) # result '0xf' 

Whilst this is clear enough for me and fits my use case (a simple test tool for a simple printer) I can't help thinking there's a lot of room for improvement and this could be squashed down to something very concise.

What other approaches are there to this problem?

like image 837
jon Avatar asked Sep 28 '12 10:09

jon


People also ask

How do I print a hex value without 0x in Python?

To print a positive or negative hexadecimal without the '0x' or '-0x' prefixes, you can simply use the string. replace('x', '0') method and replace each occurrence of 'x' with '0' .

How do you use hex in python?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.


1 Answers

Use the new .format() string method:

>>> "{0:#0{1}x}".format(42,6) '0x002a' 

Explanation:

{   # Format identifier 0:  # first parameter #   # use "0x" prefix 0   # fill with zeroes {1} # to a length of n characters (including 0x), defined by the second parameter x   # hexadecimal number, using lowercase letters for a-f }   # End of format identifier 

If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:

>>> '0x{0:0{1}X}'.format(42,4) '0x002A' 

Starting with Python 3.6, you can also do this:

>>> value = 42 >>> padding = 6 >>> f"{value:#0{padding}x}" '0x002a' 
like image 133
Tim Pietzcker Avatar answered Oct 01 '22 08:10

Tim Pietzcker