简体   繁体   中英

Python unpack binary data, numeric of length 12

I have a file with big endian binaries. There are two numeric fields. The first has length 8 and the second length 12. How can I unpack the two numbers?

I am using the Python module struct ( https://docs.python.org/2/library/struct.html ) and it works for the first field

num1 = struct.unpack('>Q',payload[0:8])

but I don't know how I can unpack the second number. If I treat it as char(12), then I get something like '\\x00\\xe3AC\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x01' .

Thanks.

I think you should create a new string of bytes for the second number of length 16, fill the last 12 bytes with the string of bytes that hold your number and first 4 ones with zeros.

Then decode the bytestring with unpack with format >QQ , let's say to numHI , numLO variables. Then, you get final number with that: number = numHI * 2^64 + numLO *. AFAIR the integers in Python can be (almost) as large as you wish, so you will have no problems with overflows. That's only rough idea, please comment if you have problems with writing that in actual Python code, I'll then edit my answer to provide more help.

*^ is in this case the math power, so please use math.pow. Alternatively, you can use byte shift: number = numHI << 64 + numLO .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM