簡體   English   中英

Python:將字符串轉換為其二進制表示形式

[英]Python: Convert a string to its binary representation

我使用Python2.7.X。
我有一個包含以下內容的文本文件

\xe87\x00\x10LOL  

請注意,這是文本本身,而不是其二進制表示形式(意味着第一個字符為“ \\\\”,而不是0xe8)當我讀取它(作為二進制形式)時,得到:

a = "\\\\xe87\\\\x00\\\\x10LOL"  

因為它是一個文本文件。

我想將其轉換為二進制形式,這意味着我想獲取一個以字符開頭的文件
0xe8、0x37、0x00、0x10、0x4c,0x4f,0x4c。
(請注意,0x4c =='L',0x4f =='O')。

我怎么做?
嘗試了諸如hexlify \\ unhexlify,int(c,16)之類的各種解決方案,但似乎我缺少了一些東西。
另請注意,文件的長度各不相同,因此,struct.pack是次要的。

使用string-escapeunicode-escape編碼

>>> content = r'\xe87\x00\x10LOL'
>>> print content
\xe87\x00\x10LOL
>>> content
'\\xe87\\x00\\x10LOL'
>>> content.decode('string-escape')
'\xe87\x00\x10LOL'
>>> map(hex, map(ord, content.decode('string-escape')))
['0xe8', '0x37', '0x0', '0x10', '0x4c', '0x4f', '0x4c']

>>> bytes(map(ord, content.decode('string-escape')))
'[232, 55, 0, 16, 76, 79, 76]'

>>> bytearray(map(ord, content.decode('string-escape')))
bytearray(b'\xe87\x00\x10LOL')

這是一種實現方法:

In [26]: a = r"\xe87\x00\x10LOL"

In [27]: b = ast.literal_eval("'" + a + "'")

In [28]: open("test.dat", "w").write(b)

In [29]: 
[1]+  Stopped                 ipython
$ xxd test.dat
0000000: e837 0010 4c4f 4c                        .7..LOL

(可能有比literal_eval更好的工具,但這是在凌晨時分想到的第一個工具。)

"".join([chr(int(i,16)) for i in data.split("\\\\x") if i])

暫無
暫無

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

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