如何在python中将单个字符转换为十六进制ascii值

时间:2022-10-30 15:04:00

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:

输出:

63

What is the simplest way of going about this? Any predefined string library stuff?

这个最简单的方法是什么?任何预定义的字符串库?

2 个解决方案

#1


57  

There are several ways of doing this:

有几种方法可以做到这一点:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

To use the hex encoding in Python 3, use

要在Python 3中使用十六进制编码,请使用

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

#2


2  

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').

此代码包含将ASCII字符转换为十六进制和从十六进制转换的示例。在你的情况下,你想要使用的行是str(binascii.hexlify(c),'ascii')。

#1


57  

There are several ways of doing this:

有几种方法可以做到这一点:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

To use the hex encoding in Python 3, use

要在Python 3中使用十六进制编码,请使用

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

#2


2  

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').

此代码包含将ASCII字符转换为十六进制和从十六进制转换的示例。在你的情况下,你想要使用的行是str(binascii.hexlify(c),'ascii')。