python pack 4-byte-integer mit der Byte im bytearray-struct.pack

Ich bin versucht zu packen, um den Inhalt eines python-bytearray in eine 4byte signed integer mit struct.pack. Leider pack will ein string, also nach etwas googlen dachte ich, ich brauchte, um zu Dekodieren, mein bytearray in einen string. Ich dachte, ascii gemeint, weil ein ascii-Zeichen ist ein byte lang. Leider ascii nicht unterstützen wollte meine Werte > 127, so dass ich dachte, ich würde verwenden, ersetzen...

aber wenn ich das mache decodieren gibt ein Objekt vom Typ unicode-und jetzt jedes meiner bytes ist eine 4-Zeichen-string...

Scheint es einfach ein wenig lächerlich, im fehlt etwas, das offensichtlich ist (ps ich habe mit python für etwa zwei Wochen)

hier ist, was ich versuche zu tun...

    val = long(-5) 
s = bytearray(pack("<i", val)) 

s.pop() # pop off msb

# write it out the way we want to then read it in the way the code does
fout = open("test.bat", "wb")
fout.write(s) 
fout.close()

fin = open("test.bat", "rb") 

inBytes = bytearray(fin.read(3))
# extend sign bit
if (inBytes[2] & 0x80):
    inBytes.append(0xff)
else:
    inBytes.append(0x00)

nb = inBytes.decode('ascii', 'replace')
# ERROR:root:after decode, len: 4 type: <type 'unicode'>
logging.error("after decode, len: {0} type: {1}".format(len(nb), type(nb)))

# struct.error: unpack requires a string argument of length 4 
inInt32 = unpack('<i', inBytes.decode('ascii', 'replace'))[0]

fin.close()

InformationsquelleAutor mike | 2011-05-20

Schreibe einen Kommentar