Decorating Hex function to pad zeros

前端 未结 6 1891
无人共我
无人共我 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: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'
    

提交回复
热议问题