Merp
Merp

Reputation: 148

Python: Binary to Base64

So I have a binary number, 001000 i.e. 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?

Upvotes: 3

Views: 1478

Answers (1)

Jaap Joris Vens
Jaap Joris Vens

Reputation: 3550

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

Upvotes: 2

Related Questions