2

I have done the following.

from struct import pack, unpack
t = 1234
tt = str(pack("<I", t))

printing tt gives \xf3\xe0\x01\x00. How do I get original value of t back from tt?

I tried using unpacking the repr(tt) but that does not work out. How do I go about doing this?

3 Answers 3

7
>>> t=1234
>>> tt=pack('<I', t)
>>> tt
'\xd2\x04\x00\x00'
>>> unpack('<I', tt)
(1234,)

>>> ttt, = unpack('<I', tt) 
>>> ttt
1234
Sign up to request clarification or add additional context in comments.

Comments

1

you are using the wrong package for serialization. the struct package is only useful for python code which interacts with C code.

for serialization into a string, you should use the pickle module.

import pickle

t = 1234
tt = pickle.dumps(t)
t = pickle.loads(tt)

4 Comments

Nobody mentioned serialisation. "Useful only for python code which interacts with C code"??? One uses struct.pack when writing binary files in some particular format and struct.unpack when reading them -- irrespective of what language may be used to read those files or may have been used to write those files originally. Using pickle instead of cPickle and using the default (text, ancient) protocol is a nonsense. Please consider deleting your answer.
@John Machin: although nobody mentioned serialisation, the title of the post implies serialisation, so i posted this answer as a hint that there exists a standard python way of serialising data. now regarding pickle/cPickle: starting with python 3, "the accelerated versions are considered implementation details of the pure Python versions. Users should always import the standard version"(from the doc). regarding the default protocol: pickle protocol version 3, which is now the default for python 3 and up, is indeed binary.
Real Programmers use Python 1.5.2
@John Machin: Real Programmers use languages that average programmers do not dare to use...
1

unpack('<I', tt) will give you (1234,).

repr doesn't work since it adds quotes to the string:

>>> repr('foo')
'"foo"'

1 Comment

unpack(tt) will give you an exception -- you need two arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.