簡體   English   中英

如何將字符串轉換為二進制?

[英]How to convert string to binary?

我需要一種在 python 中獲取字符串的二進制表示的方法。 例如

st = "hello world"
toBinary(st)

是否有一些巧妙的方式來做到這一點?

像這樣的東西?

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

如果二進制是指bytes類型,則可以只使用字符串對象的encode方法,該方法使用傳遞的編碼類型將字符串編碼為字節對象。 您只需要確保您通過正確的編碼來encode功能。

In [9]: "hello world".encode('ascii')                                                                                                                                                                       
Out[9]: b'hello world'

In [10]: byte_obj = "hello world".encode('ascii')                                                                                                                                                           

In [11]: byte_obj                                                                                                                                                                                           
Out[11]: b'hello world'

In [12]: byte_obj[0]                                                                                                                                                                                        
Out[12]: 104

否則,如果您希望它們以零和一的形式 - 二進制表示 - 作為一種更 Pythonic 的方式,您可以首先將字符串轉換為字節數組,然后在map中使用bin函數:

>>> st = "hello world"
>>> map(bin,bytearray(st))
['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100']
 

或者你可以加入它:

>>> ' '.join(map(bin,bytearray(st)))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

請注意,在python3中,您需要為bytearray函數指定編碼:

>>> ' '.join(map(bin,bytearray(st,'utf8')))
'0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100'

您還可以在 python 2 中使用binascii模塊:

>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
'0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'

hexlify返回二進制數據的十六進制表示,然后您可以通過指定 16 作為其基數將其轉換為 int ,然后使用bin將其轉換為二進制。

我們只需要對其進行編碼。

'string'.encode('ascii')

您可以使用ord()內置函數訪問字符串中字符的代碼值。 如果您隨后需要將其格式化為二進制,則string.format()方法將完成這項工作。

a = "test"
print(' '.join(format(ord(x), 'b') for x in a))

(感謝 Ashwini Chaudhary 發布該代碼片段。)

雖然上面的代碼在 Python 3 中有效,但如果您假設使用 UTF-8 以外的任何編碼,事情就會變得更加復雜。 在 Python 2 中,字符串是字節序列,默認采用 ASCII 編碼。 在 Python 3 中,字符串被假定為 Unicode,並且有一個單獨的bytes類型,其行為更像 Python 2 字符串。 如果您希望采用 UTF-8 以外的任何編碼,則需要指定編碼。

那么,在 Python 3 中,您可以執行以下操作:

a = "test"
a_bytes = bytes(a, "ascii")
print(' '.join(["{0:b}".format(x) for x in a_bytes]))

UTF-8 和 ascii 編碼之間的區別對於簡單的字母數字字符串來說並不明顯,但如果您正在處理包含不在 ascii 字符集中的字符的文本,則將變得很重要。

在 Python 3.6 及更高版本中,您可以使用f-string來格式化結果。

str = "hello world"
print(" ".join(f"{ord(i):08b}" for i in str))

01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
  • 冒號左側 ord(i) 是實際對象,其值將被格式化並插入到輸出中。 使用 ord() 為您提供單個 str 字符的 base-10 代碼點。

  • 冒號的右側是格式說明符。 08 表示寬度為 8,填充 0,b 用作符號以輸出以 2 為底的結果數字(二進制​​)。

def method_a(sample_string):
    binary = ' '.join(format(ord(x), 'b') for x in sample_string)

def method_b(sample_string):
    binary = ' '.join(map(bin,bytearray(sample_string,encoding='utf-8')))


if __name__ == '__main__':

    from timeit import timeit

    sample_string = 'Convert this ascii strong to binary.'

    print(
        timeit(f'method_a("{sample_string}")',setup='from __main__ import method_a'),
        timeit(f'method_b("{sample_string}")',setup='from __main__ import method_b')
    )

# 9.564299999998184 2.943955828988692

method_b 在轉換為字節數組時效率更高,因為它進行低級函數調用,而不是手動將每個字符轉換為整數,然后將該整數轉換為其二進制值。

這是對使用bytearray()並且不能再以這種方式工作的現有答案的更新:

>>> st = "hello world"
>>> map(bin, bytearray(st))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding

因為,如上面鏈接中所述,如果源是字符串,則還必須提供編碼

>>> map(bin, bytearray(st, encoding='utf-8'))
<map object at 0x7f14dfb1ff28>
''.join(format(i, 'b') for i in bytearray(str, encoding='utf-8'))

這可以正常工作,因為它現在很容易恢復為字符串,因為不會添加零以達到 8 位以形成一個字節,因此很容易恢復為字符串以避免刪除添加的零的復雜性。

a = list(input("Enter a string\t: "))
def fun(a):
    c =' '.join(['0'*(8-len(bin(ord(i))[2:]))+(bin(ord(i))[2:]) for i in a])
    return c
print(fun(a))

暫無
暫無

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

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