Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Using base64 to encode/decode data (See related posts)

If you have binary data, you can encode it with
ascii character to store it more safely.
base64 module is an efficient choice to do so.
It uses characters from this set
('=' is used for padding at the end.)
   1  
   2  ABCDEFGHIJKLMNOPQRSTUVWXYZ
   3  abcdefghijklmnopqrstuvwxyz
   4  0123456789+/

Here's how to use it.
   1  
   2  >>> import base64
   3  >>> base64.encodestring('hello world')
   4  'aGVsbG8gd29ybGQ=\n'
   5  >>> base64.decodestring(_)
   6  'hello world'
   7  >>>

If the text is long, the base64 module will split
the encoded data into multiple lines.
If you don't wan't it to be split. You can use
binascii.b2a_base64 instead of base64.encodestring and
binascii.a2b_base64 instead of base64.decodestring

You need to create an account or log in to post comments to this site.


Click here to browse all 5349 code snippets

Related Posts