Convert Java Byte Array To Python Byte Array
I know that if I figure this one out or if somebody shows me, it'll be a forehead slapper. Before posting any questions, I try for at least three hours and quite a bit of searching
Solution 1:
You can join it into a bytestring (just a string under python 2.x). The simplest, if not most efficient, way would be to just mod the data, then convert to chars and join. Something like:
data = [1,2,-3,-143, ...]
binData = ''.join(map(lambda x: chr(x % 256), data))
binData = ''.join(map(lambda x: chr(x % 256), attach.attcoll))
sql_stmt = """INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattachment) \
VALUES ('%s','%s','%s','%s','%s','%s') ON DUPLICATE KEY UPDATE filename='%s',fileextension='%s'""" % (attach.attno,\
attach.filename,attach.fileextension,attach.projNo,attach.procNo,binData,attach.filename,attach.fileextension)
try:
cursor.execute(sql_stmt)
conn.commit()
cursor.close()
conn.close()
return'SUCCESS'except MySQLdb.Error:
cursor.close()
conn.close()
print"My SQL cursor execute error."return'FAILURE'
Solution 2:
data = [1,2,-3,-143, ...]
binData = bytearray([x % 256 for x in data])
Solution 3:
I found ''.join(map(lambda x: chr(x % 256), data))
to be painfully slow (~4 minutes) for my data on python 2.7.9, where a small change to str(bytearray(map(lambda x: chr(x % 256), data)))
only took about 10 seconds.
Post a Comment for "Convert Java Byte Array To Python Byte Array"