Decorating Hex function to pad zeros

前端 未结 6 1857
无人共我
无人共我 2020-11-29 01:31

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 o         


        
相关标签:
6条回答
  • 2020-11-29 01:45

    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'
    
    0 讨论(0)
  • 2020-11-29 01:46

    Suppose you want to have leading zeros for hexadecimal number, for example you want 7 digit where your hexadecimal number should be written on, you can do like that :

    hexnum = 0xfff
    str_hex =  hex(hexnum).rstrip("L").lstrip("0x") or "0"
    '0'* (7 - len(str_hexnum)) + str_hexnum
    

    This gives as a result :

    '0000fff'
    
    0 讨论(0)
  • 2020-11-29 01:47

    If just for leading zeros, you can try zfill function.

    '0x' + hex(42)[2:].zfill(4) #'0x002a'
    
    0 讨论(0)
  • 2020-11-29 01:50

    How about this:

    print '0x%04x' % 42
    
    0 讨论(0)
  • 2020-11-29 02:00

    What I needed was

    "{:02x}".format(2)   # '02'
    "{:02x}".format(42)  # '2a'
    

    or as f-strings:

    f"{2:02x}"   # '02'
    f"{42:02x}"  # '2a'
    
    0 讨论(0)
  • 2020-11-29 02:02

    Use * to pass width and X for uppercase

    print '0x%0*X' % (4,42) # '0x002A'
    

    As suggested by georg and Ashwini Chaudhary

    0 讨论(0)
提交回复
热议问题