Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I convert from binary to base 64 and back?

Lets say I have some binary value:

0b100

and want to convert it to base64

doing base64.b64decode(0b100) tells me that it is expecting a string, not an int.... now, I don't want to work with strings.

So, could anyone point me in the right direction for converting binary numbers to base64 numbers? thanks!

=D

like image 718
NullVoxPopuli Avatar asked Mar 14 '11 22:03

NullVoxPopuli


People also ask

How do you convert binary to Base64?

Click on the URL button, Enter URL and Submit. This tool supports loading the Binary File to transform to Base64. Click on the Upload button and select File. Binary to Base64 Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

How do I use Base64 decoding in python?

Base64 Decoding an Image To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.

Can you reverse Base64?

Base64 decoding employs a reverse algorithm to yield the original content. While Base64 encoding alters the original content, it is not suitable as an encryption mechanism as it can be easily decoded to reveal the original content. For that there are various encryption algorithms and products to be used.


1 Answers

Depending on how you represent the value 0b100

>>> import struct
>>> val = 0b100
>>> print struct.pack('I', val).encode('base64')
BAAAAA==

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.

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.

like image 133
yan Avatar answered Sep 18 '22 20:09

yan