Reputation: 2141
I need to pack an inputted value into a struct, and to pack it as a 32-bit # (unsigned int).
An example input is '\x08\x08\x08\x08'
However, this doesn't work:
>>> s = struct.pack('I', '\x08\x08\x08\x08')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: cannot convert argument to integer
What am I doing wrong? Wrapping it as int() doesn't work:
>>> int('\x08\x08\x08\x08', 16)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: '\x08\x08\x08\x08'
I'm trying to build a struct that has other packed values before and after this one. For example, I want
inp = '\x08\x08\x08\x08'
s = struct.pack('HHIH', 50, 100, inp, 100)
to return
'2\x00d\x00\x08\x08\x08\x08d\x00'
Upvotes: 0
Views: 5054
Reputation: 70735
What - exactly - do you want as an output? struct.pack()
would return (if it worked) a string exactly like the one you passed in to begin with. struct.unpack('I', '\x08\x08\x08\x08')
returns the tuple (134744072,)
. Feed that back into struct.pack()
, and you get back the string you started with:
>>> import struct
>>> struct.unpack('I', '\x08\x08\x08\x08')
(134744072,)
>>> struct.pack('I', _[0])
'\x08\x08\x08\x08'
All this is working as documented and as expected. So please clarity what it is you want instead.
Could I just do something like struct.pack('H', somevalue) + '\x08\x08\x08\x08' + struct.pack('H', someothervalue) to make one big struct?
Maybe. It depends on things you haven't spelled out, like whether or not you're using struct
to automagically insert padding bytes (for alignment) too. If you paste the string together yourself, then you're responsible for getting that all right.
If you decide you do want to paste a 4-byte string in, then using the struct
format code 4s
is an easier way to do it.
Upvotes: 2
Reputation: 4295
The string '\x08\x08\x08\x08' is already a "packed" representation of an integer. If you want to convert it to a python integer you should try this:
struct.unpack('I','\x08\x08\x08\x08')
Of course, pay attention to endianness.
Upvotes: 0