简体   繁体   English

Python:如何将n位转换为64位?

[英]Python: How do you convert n-bits to base 64?

I have this: struct.pack('I', 0b10101010101100101010001000001000).encode('base64') which is good for converting 32 bits to base 64... but is there an easy way to convert any number of bits to base 64? 我有这个: struct.pack('I', 0b10101010101100101010001000001000).encode('base64')可以将32位转换为base 64 ...但是有一种简单的方法可以将任意数量的位转换为base 64吗?

like, anywhere between 128 and 512? 例如,介于128到512之间的任何地方?

EDIT: where I'm at: My original command: 编辑:我在哪里:我的原始命令:

>>> struct.pack('I', 0b10101010101100101010001000001000).encode('base64')  
'CKKyqg==\n'

One of the suggestions is to use \\x for hex and convert that... so far so good. 建议之一是将\\ x用作十六进制并将其转换...到目前为止效果很好。

>>> struct.pack('I', 0b10101010101100101010001000001000).encode('hex')
'08a2b2aa'
>>> '\x08\xa2\xb2\xaa'.encode('base64')
'CKKyqg==\n'

but can I do the samething with binary? 但是我可以对二进制文件做同样的事情吗?

>>> '\b10101010\b10110010\b10100010\b00001000'.encode('base64')
'CDEwMTAxMDEwCDEwMTEwMDEwCDEwMTAwMDEwCDAwMDAxMDAw\n'
nope =(

If you have an arbitrary-long binary string, use string hex escapes: 如果您有一个任意长的二进制字符串,请使用字符串十六进制转义:

'\x00\x01\x02\x03'.encode('base64')

So your example would be: 因此,您的示例将是:

'\xaa\xb2\xa2\x08'.encode('base64')

I have written an article which describes a simple solution in Python which can be used to transfrom a series of numbers from and to arbitrary number bases. 我写了一篇文章 ,描述了Python中的一个简单解决方案,该解决方案可用于将一系列数字与任意数字基数相互转换。 Using the proposed solution you could transform a list of binary digits into any encoding representation you like. 使用建议的解决方案,您可以将二进制数字列表转换为您喜欢的任何编码表示形式。 Note however, that the result of a conversion will not contain padding characters as it just doesn't need them. 但是请注意,转换结果将不包含填充字符,因为它不需要它们。 Maybe it serves your needs, maybe not ;) 也许它满足您的需求,也许不是;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM