Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created September 23, 2011 13:56
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save igniteflow/1237391 to your computer and use it in GitHub Desktop.
Save igniteflow/1237391 to your computer and use it in GitHub Desktop.
Python binary string compatible with Java byte array (as used in SOAP web services)
import base64
"""
Some useful functions for interacting with Java web services from Python.
"""
def make_file_java_byte_array_compatible(file_obj):
"""
Reads in a file and converts it to a format accepted as Java byte array
:param file object
:return string
"""
encoded_data = base64.b64encode(file_obj.read())
strg = ''
for i in xrange((len(encoded_data)/40)+1):
strg += encoded_data[i*40:(i+1)*40]
return strg
def java_byte_array_to_binary(file_obj):
"""
Converts a java byte array to a binary stream
:param java byte array as string (pass in as a file like object, can use StringIO)
:return binary string
"""
decoded_data = base64.b64decode(file_obj.read())
strg = ''
for i in xrange((len(decoded_data)/40)+1):
strg += decoded_data[i*40:(i+1)*40]
return strg
@nicolasmendoza
Copy link

Thanks!

@gaquino
Copy link

gaquino commented Sep 29, 2017

Thx, it’s very useful.

Have you used it on python3? I tried the same logic you had used but seems that range works different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment