如何将字符串中的字节转换为整数?蟒蛇

时间:2022-07-01 20:13:32

I want to get a list of ints representing the bytes in a string.

我想获得一个表示字符串中字节的整数列表。

3 个解决方案

#1


7  

One option for Python 2.6 and later is to use a bytearray:

Python 2.6及更高版本的一个选项是使用bytearray:

>>> b = bytearray('hello')
>>> b[0]
104
>>> b[1]
101
>>> list(b)
[104, 101, 108, 108, 111]

For Python 3.x you'd need a bytes object rather than a string in any case and so could just do this:

对于Python 3.x,在任何情况下都需要一个字节对象而不是字符串,因此可以这样做:

>>> b = b'hello'
>>> list(b)
[104, 101, 108, 108, 111]

#2


5  

Do you mean the ascii values?

你的意思是ascii值吗?

nums = [ord(c) for c in mystring]

or

要么

nums = []
for chr in mystring:
    nums.append(ord(chr))

#3


2  

Perhaps you mean a string of bytes, for example received over the net, representing a couple of integer values?

也许你的意思是一串字节,例如通过网络接收,代表几个整数值?

In that case you can "unpack" the string into the integer values by using unpack() and specifying "i" for integer as the format string.

在这种情况下,您可以使用unpack()并将整数指定为“i”作为格式字符串,将字符串“解包”为整数值。

See: http://docs.python.org/library/struct.html

请参阅:http://docs.python.org/library/struct.html

#1


7  

One option for Python 2.6 and later is to use a bytearray:

Python 2.6及更高版本的一个选项是使用bytearray:

>>> b = bytearray('hello')
>>> b[0]
104
>>> b[1]
101
>>> list(b)
[104, 101, 108, 108, 111]

For Python 3.x you'd need a bytes object rather than a string in any case and so could just do this:

对于Python 3.x,在任何情况下都需要一个字节对象而不是字符串,因此可以这样做:

>>> b = b'hello'
>>> list(b)
[104, 101, 108, 108, 111]

#2


5  

Do you mean the ascii values?

你的意思是ascii值吗?

nums = [ord(c) for c in mystring]

or

要么

nums = []
for chr in mystring:
    nums.append(ord(chr))

#3


2  

Perhaps you mean a string of bytes, for example received over the net, representing a couple of integer values?

也许你的意思是一串字节,例如通过网络接收,代表几个整数值?

In that case you can "unpack" the string into the integer values by using unpack() and specifying "i" for integer as the format string.

在这种情况下,您可以使用unpack()并将整数指定为“i”作为格式字符串,将字符串“解包”为整数值。

See: http://docs.python.org/library/struct.html

请参阅:http://docs.python.org/library/struct.html