struct - Error Packing and Unpacking bytes in Python -
my code has error(see below code) after enter in value. can pack bits unpacking doesn't work. suggestions? don't understand packing , unpacking , documentation bit confusing.
import struct #binaryadder - def binaryadder(input): input = int(input) d = struct.pack("<i", input) print d print type(d) d = struct.unpack("<i",input) print d #test pack count = 0 while true: print "enter input" = raw_input() binaryadder(a) count = count + 1 print "while loop #%s finished\n" % count
this code throws following error after enter in string:
enter input 900 รค <type 'str'> traceback (most recent call last): file "c:\pythonpractice\binarygenerator.py", line 25, in <module> binaryadder(a) file "c:\pythonpractice\binarygenerator.py", line 17, in binaryadder d = struct.unpack("<i",input) struct.error: unpack requires string argument of length 4
d = struct.pack("<i", input)
this packs input string; entered number 900
packed string '\x84\x03\x00\x00'
.
then, bit later, this:
d = struct.unpack("<i",input)
now attempt unpack same input, still 900
. obviously, doesn’t work since need unpack string. in case, want unpack d
packed before. try this:
unpacked_d = struct.unpack("<i", d)
unpacked_d
should contain number input
.
Comments
Post a Comment