开发者

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?

like, anywhere between 128 and 512?

EDIT: where I'm at: My original command:

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

One of the suggest开发者_如何转开发ions is to use \x for hex and convert that... so far so good.

>>> 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. 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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜