Python 2,3 将整数干净地转换为“字节”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14043886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:15:13  来源:igfitidea点击:

Python 2,3 Convert Integer to "bytes" Cleanly

python

提问by imallett

The shortest ways I have found are:

我发现的最短方法是:

n = 5

# Python 2.
s = str(n)
i = int(s)

# Python 3.
s = bytes(str(n), "ascii")
i = int(s)

I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible.

我特别关心两个因素:可读性和可移植性。对于 Python 3,第二种方法很丑陋。但是,我认为它可能向后兼容。

Is there a shorter, cleaner way that I have missed? I currently make a lambda expression to fix it with a new function, but maybe that's unnecessary.

有没有我错过的更短、更干净的方式?我目前制作了一个 lambda 表达式来用一个新函数修复它,但这也许是不必要的。

采纳答案by Mark Ransom

Answer 1:

答案 1:

To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's encodemethod. If you don't supply an encoding parameter 'ascii'is used, which will always be good enough for numeric digits.

要将字符串转换为 Python 2 或 Python 3 中的字节序列,请使用字符串的encode方法。如果您不提供使用编码参数'ascii',这对于数字总是足够好。

s = str(n).encode()

In Python 2 str(n)already produces bytes; the encodewill do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.

在 Python 2 中str(n)已经产生了字节;该encode会是一个双转换与此字符串隐式转换为Unicode,然后再返回到字节。这是不必要的工作,但它是无害的,并且与 Python 3 完全兼容。



Answer 2:答案 2:

Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a differentquestion, I'll answer that question too. If you want to convert 10to b'10'use the answer above, but if you want to convert 10to b'\x0a\x00\x00\x00'then keep reading.

以上是实际提出的问题的答案,即以人类可读的形式生成一串 ASCII 字节。但由于人们不断来到这里试图得到不同问题的答案,我也会回答这个问题。如果您想转换10b'10'使用上面的答案,但如果您想转换10为,b'\x0a\x00\x00\x00'请继续阅读。

The structmodulewas specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with struct.pack. There's a format parameter fmtthat determines which conversion it should perform. For a 4-byte integer, that would be ifor signed numbers or Ifor unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment tablefor options when the output is more than a single byte.

struct模块专门用于在各种类型之间进行转换,并将其二进制表示为字节序列。从类型到字节的转换是通过struct.pack. 有一个格式参数fmt决定它应该执行哪种转换。对于 4 字节整数,这将i用于有符号数或I无符号数。有关更多可能性,请参阅格式字符表,并在输出超过单个字节时查看选项的字节顺序、大小和对齐表

import struct
s = struct.pack('<i', 5) # b'\x05\x00\x00\x00'

回答by Nadu

Converting an intto a bytein Python 3:

转换的INT字节在Python 3

    n = 5    
    bytes( [n] )

>>> b'\x05'

;) guess that'll be better than messing around with strings

;) 猜想这比乱搞字符串要好

source: http://docs.python.org/3/library/stdtypes.html#binaryseq

来源:http: //docs.python.org/3/library/stdtypes.html#binaryseq

回答by Andy Hayden

You can use the struct's pack:

您可以使用结构包

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian)and the "I" is the format character. So you can be specific if you want to do something else:

">" 是字节顺序 (big-endian),而 "I" 是格式字符。因此,如果您想做其他事情,则可以具体说明:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

这在 python 2 和python 3上的工作原理相同。

Note: the inverse operation (bytes to int) can be done with unpack.

注意:逆操作(字节到整数)可以用unpack完成。

回答by alex.forencich

I have found the only reliable, portable method to be

我发现唯一可靠、便携的方法是

bytes(bytearray([n]))

Just bytes([n]) does not work in python 2. Taking the scenic route through bytearray seems like the only reasonable solution.

仅 bytes([n]) 在 python 2 中不起作用。通过 bytearray 走风景路线似乎是唯一合理的解决方案。

回答by Sunber

from int to byte:

从整数到字节:

bytes_string = int_v.to_bytes( lenth, endian )

where the lenth is 1/2/3/4...., and endian could be 'big' or 'little'

其中长度为 1/2/3/4 ....,并且字节序可以是“大”或“小”

form bytes to int:

将字节转换为整数:

data_list = list( bytes );

回答by retsigam

In Python 3.x, you can convert an integer value (including large ones, which the other answers don't allow for) into a series of bytes like this:

在 Python 3.x 中,您可以将整数值(包括其他答案不允许的大值)转换为一系列字节,如下所示:

import math

x = 0x1234
number_of_bytes = int(math.ceil(x.bit_length() / 8))

x_bytes = x.to_bytes(number_of_bytes, byteorder='big')

x_int = int.from_bytes(x_bytes, byteorder='big')
x == x_int