在Python中将十六进制字符转换为int

发布于 2024-11-05 00:34:03 字数 463 浏览 1 评论 0原文

我正在使用图形库 Pyglet 进行一些绘图,并希望将结果图像输出为Python 列表(这样我可以将其转换为 NumPy 数组)。

Pyglet 给我一串十六进制字符,如下所示:'\xff'(表示一个像素处的值为 255)。如何将这样的字符串转换为 int?

我尝试过 int('\xff', 16),但这不起作用。请注意,根据 文档, '\xnn' 被转义和编码作为十六进制字符,但它没有告诉我如何将其转换为 int。

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 gives me a string of hex characters, like this: '\xff' (indicating a value of 255 at one pixel). How can I convert such a string to an int?

I've tried int('\xff', 16), but that doesn't work. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

铁轨上的流浪者 2024-11-12 00:34:03

要直接从 Python 字符串获取 NumPy 数组,您可以使用

s = "\xff\x03"
a = numpy.frombuffer(s, numpy.uint8)

要获取列表,您可以使用

a =  map(ord, s)

Python 2.6 或更高版本中列表的替代方法是使用 bytesarray(s)

To get a NumPy array straight from a Python string, you can use

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

囍孤女 2024-11-12 00:34:03

尝试这样的操作:

a = '\xff'
print int(a.encode('hex'), 16)
255

编辑:抱歉,以前的版本有一个错误 - 解码而不是编码。这有效。

编辑2:正如评论者指出的那样,我实际上误读了这个问题。这可能已经很明显了,但如果有人发现它有帮助,常规的 python 列表解决方案将是:

>>> a = '\xff\xfe'
>>> [str(ord(char)) for char in a]
['255', '254']
>>> ' '.join([str(ord(char)) for char in a])
'255 254'

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. This may be already obvious but in case someone finds it helpful the regular python list solution would be:

>>> a = '\xff\xfe'
>>> [str(ord(char)) for char in a]
['255', '254']
>>> ' '.join([str(ord(char)) for char in a])
'255 254'
九厘米的零° 2024-11-12 00:34:03

这是处理具有可变长度子字符串的十六进制字符串的通用方法,例如:

s = '5b1\n5\n3ad44'

以下代码通过矢量化在 2 秒内(在 MacBook 上)将具有 300 万个可变长度十六进制子字符串的字符串转换为 numpy 整数数组:

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]

Here's a generalised approach that handles a hex string with variable length substrings, e.g.:

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:

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]
浅听莫相离 2024-11-12 00:34:03

是的,\xff 是字节中十六进制值的打印表示。但是 int() 不适用于字节的十六进制表示,但适用于数字的字符串表示。 16 进制世界中的数字是“13”或“ab”或“ff”。因此(但仍然有趣),int('ff',16) 工作得很好。如果你想走这条路,你需要去掉 '\x':-)。

Yes, \xff is the print representation of a hex value in a byte. But int() doesn't work on hex representations of bytes, but on string representation of numbers. A number in the base-16 world is '13' or 'ab' or 'ff'. Consequently (but still funnily), int('ff',16) works fine. If you want to go that route, you need to get rid of the '\x' :-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文