1

I'm trying to unpack bytes in python :-

import struct


c_struct_exp='struct lokesh { int i=5;} lm;'
result=struct.unpack('!i',bytes(c_struct_exp,'utf-8'))  
print(result)

error:

 struct.error: unpack requires a bytes object of length 4

please, help me with format string expression in unpack method.

1 Answer 1

3

unpack is for unpacking binary data, not C source code. To follow your example of single integer member structure:

>>> from struct import *
>>> pack('i', 134)
'\x86\x00\x00\x00'
>>> unpack('i', '\x86\x00\x00\x00')
(134,)
>>>
Sign up to request clarification or add additional context in comments.

3 Comments

I'm not using C source code directly. I'm converting c source code into raw bytes :- bytes(c_struct_exp,'utf-8') before using it in unpack methode..
Try printing the output of your bytes(...) call - it's still source code. unpack decodes memory image of a structure, not its source description.
okk :) got it... actually i'm trying to decode a C struct packet from a C client at server side(python receiving end).. how can i can decode unpack received raw bytes(C struct,which is memory image and not a source code at client side)... how can i unpack a structure of the above type :- typedef struct packet{ int command; union{ struct{int data[100]; int ttl[100];}; struct{ char config[256]; };};} myPacketStruct;

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.