Alex
Alex

Reputation: 5

Error Packing and Unpacking bytes in Python

My code has an error(see below code) after I enter in a value. I can pack the bits but the unpacking doesn't work. Any suggestions? I don't fully understand the packing and unpacking and the documentation is a 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"
    a = raw_input()
    binaryadder(a)
    count = count + 1
    print "While Loop #%s finished\n" % count 

This code throws back the following error after I enter in a 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 a string argument of length 4

Upvotes: 0

Views: 852

Answers (1)

poke
poke

Reputation: 388413

d = struct.pack("<I", input)

This packs the input into a string; so the entered number 900 is packed into the string '\x84\x03\x00\x00'.

Then, a bit later, you do this:

d = struct.unpack("<I",input)

Now you attempt to unpack the same input, which is still 900. Obviously, that doesn’t work since you need to unpack a string. In your case, you likely want to unpack d which is what you packed before. So try this:

unpacked_d = struct.unpack("<I", d)

unpacked_d should then contain the number that was input.

Upvotes: 1

Related Questions