Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a string from a struct?

So I have the string john. I pack it into a struct. When I unpack it, how can I print john? Currently it only prints j. Same thing if I changed the string to Sammy or other names with different lengths? I have 2 functions to pack and unpack the struct. This what I don't need to worry about the lengths of the first_name's. The function can do it for me.

The structure is basically

  • user_id (in this case 1)
  • first_name (a person first name. This string can be of different lengths. In this case john)

My Code

from struct import *

def make_struct(user_id, first_name):
    return pack("is", user_id, first_name)

def deconstruct_struct(structure):
    return unpack("is", structure)

packed = make_struct(1, "john")
unpacked = deconstruct_struct(packed)

print(unpacked[1])

Current output is:

j
like image 523
Mary Avatar asked Sep 10 '26 17:09

Mary


1 Answers

You need to add the length of the string to the format string:

packed = pack("i4s", 1, "john")
unpacked = unpack("i4s", packed)
print(unpacked[1])
>> john

If you need a string of variable length -> packing and unpacking variable length array/string using the struct module in python

EDIT:

Your solution can be extended like this:

from struct import *

def make_struct(user_id, first_name):
    first_name_length = len(first_name)
    fmt = "ii{}s".format(first_name_length) #generate format string with length of first_name
    return pack(fmt, user_id, first_name_length, first_name) #add the length to the pack

def deconstruct_struct(structure):
    user_id, first_name_length = unpack("ii", structure[:8]) #extract only userid and length from the pack
    fmt = "ii{}s".format(first_name_length) #generate the format string like above
    #return unpack(fmt, structure) #this would return a (user_id, length of first name, first_name) tuple
    return (user_id, unpack(fmt, structure)[2]) #this way, we return only the (user_id, first_name) tuple

packed = make_struct(1, "john")
unpacked = deconstruct_struct(packed)
like image 163
Reductio Avatar answered Sep 13 '26 06:09

Reductio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!