简体   繁体   中英

Python: Binary to Base64

So I have a binary number, 001000 ie 8 .

If I do base64.b64encode(001000) I get an error.

So I do base64.b64encode(b'001000') and I get b'MDAxMDAw' .

But I need to get the base64 character in the index of the original number, 001000 or 8, which in this case would be 'I' . Or if the number was 011100 (28), then the corresponding character on the base64 table with a value of 28 would be: 'd' .

For example: here are some values in the b64 table

0 == A, 1 == B, 2 == C, 3 == D, 4 == E

So what I want to do is: First, convert the binary number to decimal (000011 == 3) . Then take that number and compare it to the base64 table, and you will see that 3 or 000011 , is equal to 'D' .

Does anyone know how I could do this?

If I understand correctly, the following should do what you want:

base64.b64encode(bytes([0b001000]))

Explanation:

  • 0b001000 : the 0b notation returns the integer 8
  • [0b001000] : creates an array of length 1
  • bytes([0b001000]) : converts an iterable to bytes
  • b64encode(bytes([0b001000])) : converts these bytes to base64 encoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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