[英]Converting a hexadecimal character to an int in Python
I'm using the graphics library Pyglet to do some drawing and want to get the resulting image out as a Python list (so I can convert it to a NumPy array).我正在使用图形库Pyglet进行一些绘图,并希望将生成的图像作为 Python 列表(所以我可以将其转换为NumPy数组)。
Pyglet gives me a string of hex characters, like this: '\xff' (indicating a value of 255 at one pixel). Pyglet 给了我一串十六进制字符,如下所示:'\xff'(表示一个像素的值为 255)。 How can I convert such a string to an int?
如何将这样的字符串转换为 int?
I've tried int('\xff', 16), but that doesn't work.我试过 int('\xff', 16),但这不起作用。 Note that according to the documentation , '\xnn' is escaped and encoded as a hexedecimal char, but it doesn't tell me how to convert that to an int.
请注意,根据文档,'\xnn' 被转义并编码为十六进制字符,但它没有告诉我如何将其转换为 int。
To get a NumPy array straight from a Python string, you can use要直接从 Python 字符串获取 NumPy 数组,您可以使用
s = "\xff\x03"
a = numpy.frombuffer(s, numpy.uint8)
To get a list you can use要获取列表,您可以使用
a = map(ord, s)
An alternative to a list in Python 2.6 or above is to use bytesarray(s)
. Python 2.6 或更高版本中的列表的替代方法是使用
bytesarray(s)
。
Try something like this:尝试这样的事情:
a = '\xff'
print int(a.encode('hex'), 16)
255
Edit: sorry, the previous version had a mistake - decode instead of encode.编辑:对不起,以前的版本有一个错误 - 解码而不是编码。 This works.
这行得通。
Edit 2: I actually misread the question, as commenters noted.编辑2:正如评论者指出的那样,我实际上误读了这个问题。 This may be already obvious but in case someone finds it helpful the regular python list solution would be:
这可能已经很明显了,但如果有人发现它有帮助,常规的 python 列表解决方案将是:
>>> a = '\xff\xfe'
>>> [str(ord(char)) for char in a]
['255', '254']
>>> ' '.join([str(ord(char)) for char in a])
'255 254'
Here's a generalised approach that handles a hex string with variable length substrings, eg:这是一种处理具有可变长度子字符串的十六进制字符串的通用方法,例如:
s = '5b1\n5\n3ad44'
The following code transforms a string with 3 million variable length hex substrings to a numpy integer array in 2 seconds (on a MacBook) through vectorisation:以下代码通过向量化在 2 秒内(在 MacBook 上)将具有 300 万个可变长度十六进制子字符串的字符串转换为 numpy integer 数组:
import numpy as np, pandas as pd, cStringIO
s = ('5b1\n5\n3ad44\n' * 1000000)[:-1] # 3m item hex string (variable element length)
# change hex to 2 digit decimal
for i in range(0,9): s = s.replace(str(i),'0' + str(i))
for i in [['a','10'],['b','11'],['c','12'],['d','13'],['e','14'],['f','15']]:
s = s.replace(i[0],i[1])
# read string into numpy
n = np.array(pd.read_csv(cStringIO.StringIO(s), header=None)[[0]]).astype('int64')
# fix base
n = (n % 100) + 16 * ((n % 10000)/100) + 256 * ((n % 1000000)/10000) + 4096 * ((n % 100000000)/1000000) + 65536 * ((n % 10000000000)/100000000)
n[0:3] # confirm correct transformation to [1457, 5, 240964]
Yes, \xff
is the print representation of a hex value in a byte.是的,
\xff
是以字节为单位的十六进制值的打印表示。 But int()
doesn't work on hex representations of bytes, but on string representation of numbers.但是
int()
不适用于字节的十六进制表示,而是数字的字符串表示。 A number in the base-16 world is '13' or 'ab' or 'ff'. base-16 世界中的数字是“13”或“ab”或“ff”。 Consequently (but still funnily),
int('ff',16)
works fine.因此(但仍然很有趣),
int('ff',16)
工作正常。 If you want to go that route, you need to get rid of the '\x':-).如果你想 go 那条路线,你需要去掉'\x':-)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.