問題描述
假設我有一些二進制值:
Lets say I have some binary value:
0b100
并希望將其轉換為 base64
and want to convert it to base64
執行 base64.b64decode(0b100)
告訴我它需要一個字符串,而不是一個 int....現在,我不想使用字符串.
doing base64.b64decode(0b100)
tells me that it is expecting a string, not an int.... now, I don't want to work with strings.
那么,誰能指出我將二進制數轉換為 base64 數的正確方向?謝謝!
So, could anyone point me in the right direction for converting binary numbers to base64 numbers? thanks!
=D
推薦答案
取決于你如何表示值 0b100
>>> import struct
>>> val = 0b100
>>> print struct.pack('I', val).encode('base64')
BAAAAA==
這會將您的值轉換為原生字節序的 4 字節整數,并將該值編碼為 base64.您需要指定數據的寬度,因為 base64 確實用于以可打印字符表示二進制數據.
This will turn your value into a 4-byte integer in native endianness, and encode that value into base64. You need to specify the width of your data as base64 is really made for representing binary data in printable characters.
您通常可以通過 struct 的函數將數據編碼為一串字節,然后編碼為 base64.確保在解碼時使用相同的數據布局和字節序.
You can typically encode data as a string of bytes via struct's functions, and then encode into base64. Ensure you're using the same data layout and endianess when decoding.
這篇關于Python:如何從二進制轉換為 base 64 并返回?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!