Literal Escaped Octets

Bengt Richter bokr at oz.net
Tue Feb 7 10:06:49 EST 2006


On Mon, 06 Feb 2006 04:40:31 GMT, Chason Hayes <chasonh at hotmail.com> wrote:

>I am trying to convert raw binary data to data with escaped octets in
>order to store it in a bytea field on postgresql server. I could do this
>easily in c/c++ but I need to do it in python. I am not sure how to read
>and evaluate the binary value of a byte in a long string when it is a non
>printable ascii value in python. I read some ways to use unpack from the
>struct module, but i really couldn't understand where that would help. I
>looked at the MIMIEncode module but I don't know how to convert the object
>to a string. Is there a module that will convert the data? It seems to me
>that this question must have been answered a million times before but I
>can't find anything.
>
Have you considered just encoding the data as text in hex or base64, e.g.,

 >>> import binascii
 >>> s = '\x00\x01\x02\x03ABCD0123'
 >>> binascii.hexlify(s)
 '000102034142434430313233'
 >>> binascii.b2a_base64(s)
 'AAECA0FCQ0QwMTIz\n'

which is also reversible later of course:
 >>> h = binascii.hexlify(s)
 >>> binascii.unhexlify(h)
 '\x00\x01\x02\x03ABCD0123'
 >>> b64 = binascii.b2a_base64(s)
 >>> binascii.a2b_base64(b64)
 '\x00\x01\x02\x03ABCD0123'

Regards,
Bengt Richter



More information about the Python-list mailing list