簡體   English   中英

如何在Python中將0x1b87打印為\\ x1b \\ x87?

[英]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'

我將使用format(..., 'x')進行十六進制表示,避免不必要的切片( hex(...)[2:] )。

Python 2

只需解碼字符串(使用hex編解碼器):

>>> format(0x0d90 ^ 0x1617, 'x').decode('hex')
'\x1b\x87'

或者使用struct.pack打包整數( >對於big-endian順序, H表示unsigned short - 更改格式字符以滿足您的要求)

>>> import struct
>>> struct.pack('>H', 0x0d90 ^ 0x1617)
'\x1b\x87'

Python 3

bytes.fromhex做到了:

In [1]: bytes.fromhex(format(0x0d90 ^ 0x1617, 'x'))
Out[1]: b'\x1b\x87'

struct.pack仍然是一個選項, 格式字符串與Python 2一樣(參見上一節):

In [2]: import struct

In [3]: struct.pack('>H', 0x0d90 ^ 0x1617)
Out[3]: b'\x1b\x87'

hex編解碼器現在是二進制轉換之一 ,使用codecs.decode

In [4]: import codecs

In [5]: codecs.decode(format(0x0d90 ^ 0x1617, 'x'), 'hex')
Out[5]: b'\x1b\x87'

Python 3.2和更新版本

Python 3.2引入了很酷的int.to_bytes方法:

In [4]: (0x0d90 ^ 0x1617).to_bytes(4, 'big')
Out[4]: b'\x00\x00\x1b\x87'

它將產生固定數量的字節(在本例中為4 )或OverflowError “如果整數不能用給定的字節數表示”。

有一種方法可以計算表示整數所需的最小字節數:

In [22]: i = 0x0d90 ^ 0x1617

In [23]: i.to_bytes((i.bit_length() // 8) + 1, 'big')
Out[23]: b'\x1b\x87'

另外,請考慮指定signed參數

確定是否使用二進制補碼來表示整數。 如果signedFalse且給出了負整數,則引發OverflowError

import struct
struct.pack(">H" ,int('0x1b87',16))

'\x1b\x87'
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM