Convert Java byte array to Python byte array

自闭症网瘾萝莉.ら 提交于 2019-12-14 02:20:46

问题


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. There are several hints that are close, but nothing I have adopted/tried seems to work.

I am taking a byte[] from Java and passing that via JSON (with Gson) to a python JSON using Flask. This byte[] is stored in a python object as an integer list when received, but now I need to send it to MySQLdb and store it as a blob. The data contents is binary file data.

How do I convert a python integer list [1,2,-3,-143....] to something that I can store in MySQL? I have tried bytearray() and array.array(), but those choke when I access the list directly from the object and try and convert to a string to store thorugh MySQLdb.

Any links or hints are greatly appreciated.


回答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'



回答2:


data = [1,2,-3,-143, ...]
binData = bytearray([x % 256 for x in data])



回答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.



来源:https://stackoverflow.com/questions/5088671/convert-java-byte-array-to-python-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!