How do I convert a single character into it's hex ascii value in python

前端 未结 2 1011
感情败类
感情败类 2020-12-23 19:25

I am interested in taking in a single character,

c = \'c\' # for example
hex_val_string = char_to_hex_string(c)
print hex_val_string

output

相关标签:
2条回答
  • 2020-12-23 20:04

    To use the hex encoding in Python 3, use

    >>> import codecs
    >>> codecs.encode(b"c", "hex")
    b'63'
    

    In legacy Python, there are several other ways of doing this:

    >>> hex(ord("c"))
    '0x63'
    >>> format(ord("c"), "x")
    '63'
    >>> "c".encode("hex")
    '63'
    
    0 讨论(0)
  • 2020-12-23 20:05

    This might help

    import binascii
    
    x = b'test'
    x = binascii.hexlify(x)
    y = str(x,'ascii')
    
    print(x) # Outputs b'74657374' (hex encoding of "test")
    print(y) # Outputs 74657374
    
    x_unhexed = binascii.unhexlify(x)
    print(x_unhexed) # Outputs b'test'
    
    x_ascii = str(x_unhexed,'ascii')
    print(x_ascii) # Outputs test
    

    This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

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