Format ints into string of hex

前端 未结 10 1741
陌清茗
陌清茗 2020-11-30 08:16

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.

相关标签:
10条回答
  • 2020-11-30 08:50

    Example with some beautifying, similar to the sep option available in python 3.8

    def prettyhex(nums, sep=''):
        return sep.join(f'{a:02x}' for a in nums)
    
    numbers = [0, 1, 2, 3, 127, 200, 255]
    print(prettyhex(numbers,'-'))
    

    output

    00-01-02-03-7f-c8-ff
    
    0 讨论(0)
  • 2020-11-30 08:51

    With python 2.X, you can do the following:

    numbers = [0, 1, 2, 3, 127, 200, 255]
    print "".join(chr(i).encode('hex') for i in numbers)
    

    print

    '000102037fc8ff'
    
    0 讨论(0)
  • 2020-11-30 08:51

    From Python documentation. Using the built in format() function you can specify hexadecimal base using an 'x' or 'X' Example:

    x= 255 print('the number is {:x}'.format(x))

    Output:

    the number is ff

    Here are the base options

    Type
    'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd'.

    0 讨论(0)
  • 2020-11-30 08:54

    Python 2:

    >>> str(bytearray([0,1,2,3,127,200,255])).encode('hex')
    '000102037fc8ff'
    

    Python 3:

    >>> bytearray([0,1,2,3,127,200,255]).hex()
    '000102037fc8ff'
    
    0 讨论(0)
  • 2020-11-30 09:05
    ''.join('%02x'%i for i in input)
    
    0 讨论(0)
  • 2020-11-30 09:08

    Yet another option is binascii.hexlify:

    a = [0,1,2,3,127,200,255]
    print binascii.hexlify(bytes(bytearray(a)))
    

    prints

    000102037fc8ff
    

    This is also the fastest version for large strings on my machine.

    In Python 2.7 or above, you could improve this even more by using

    binascii.hexlify(memoryview(bytearray(a)))
    

    saving the copy created by the bytes call.

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