How to convert arbitrary objects directly to base64 without initial string conversion?

Russell Warren russandheather at gmail.com
Thu Jul 13 10:41:00 EDT 2006


I've got a case where I want to convert binary blocks of data (various
ctypes objects) to base64 strings.

The conversion calls in the base64 module expect strings as input, so
right now I'm converting the binary blocks to strings first, then
converting the resulting string to base64.  This seems highly
inefficient and I'd like to just go straight from binary to a base64
string.

Here is the conversion we're using from object to string...

import ctypes
def ObjAsString(obj):
  sz = ctypes.sizeof(obj)
  charArray = ctypes.c_char * sz
  buf = charArray.from_address(ctypes.addressof(obj))
  return buf.raw[:sz]

The returned string can then be sent to base64 for conversion (although
we're actually using xmlrpc.Binary), but there is obviously some waste
in here.

import base64
b64 = base64.b64encode(ObjAsString(foo))

Is there a canned/pre-existing way to convert a block of memory to a
base64 string more efficiently?  I'd like to avoid writing my own
base64 conversion routine if possible.  Anyone have any good ideas?
Even a mroe efficient/less clunky way of conevrting an arbitrary object
to a string would be appreciated.

Thanks,
Russ




More information about the Python-list mailing list