[英]How can I get 0x1b87 to print like \x1b\x87 in Python?
How can I get 0x1b87
to print like \\x1b\\x87
in Python? 如何在Python
0x1b87
打印为\\x1b\\x87
?
$ python
Python 2.7.9 (default, Apr 2 2015, 15:33:21)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hex(0x0d90 ^ 0x1617)
'0x1b87'
I'm going to use format(..., 'x')
for hexadecimal representation, avoiding the unnecessary slicing ( hex(...)[2:]
). 我将使用
format(..., 'x')
进行十六进制表示,避免不必要的切片( hex(...)[2:]
)。
Just decode the string (using the hex
codec): 只需解码字符串(使用
hex
编解码器):
>>> format(0x0d90 ^ 0x1617, 'x').decode('hex')
'\x1b\x87'
or pack the integer with struct.pack
( >
for big-endian order, H
for unsigned short
- change format character to meet your requirements) 或者使用
struct.pack
打包整数( >
对于big-endian顺序, H
表示unsigned short
- 更改格式字符以满足您的要求)
>>> import struct
>>> struct.pack('>H', 0x0d90 ^ 0x1617)
'\x1b\x87'
bytes.fromhex
does that: bytes.fromhex
做到了:
In [1]: bytes.fromhex(format(0x0d90 ^ 0x1617, 'x'))
Out[1]: b'\x1b\x87'
struct.pack
is still an option, format strings are as for Python 2 (see the previous section): struct.pack
仍然是一个选项, 格式字符串与Python 2一样(参见上一节):
In [2]: import struct
In [3]: struct.pack('>H', 0x0d90 ^ 0x1617)
Out[3]: b'\x1b\x87'
The hex
codec is now one of the binary transforms , use codecs.decode
: hex
编解码器现在是二进制转换之一 ,使用codecs.decode
:
In [4]: import codecs
In [5]: codecs.decode(format(0x0d90 ^ 0x1617, 'x'), 'hex')
Out[5]: b'\x1b\x87'
Python 3.2 introduced the cool int.to_bytes
method: Python 3.2引入了很酷的
int.to_bytes
方法:
In [4]: (0x0d90 ^ 0x1617).to_bytes(4, 'big')
Out[4]: b'\x00\x00\x1b\x87'
It will produce a fixed number of bytes ( 4 in this example) or the OverflowError
"if the integer is not representable with the given number of bytes". 它将产生固定数量的字节(在本例中为4 )或
OverflowError
“如果整数不能用给定的字节数表示”。
There's a way to calculate the minimum number of bytes necessary to represent the integer: 有一种方法可以计算表示整数所需的最小字节数:
In [22]: i = 0x0d90 ^ 0x1617
In [23]: i.to_bytes((i.bit_length() // 8) + 1, 'big')
Out[23]: b'\x1b\x87'
Also, consider specifying the signed
argument that 另外,请考虑指定
signed
参数
determines whether two's complement is used to represent the integer.
确定是否使用二进制补码来表示整数。 If signed is False and a negative integer is given, an OverflowError is raised.
如果signed为False且给出了负整数,则引发OverflowError 。
import struct
struct.pack(">H" ,int('0x1b87',16))
'\x1b\x87'
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.