Struct module in Python ! Pack and unpack | Sololearn: Learn to code for FREE!


Struct module in Python ! Pack and unpack

import struct , it is a python module comes with distro .it can pack and unpack any data . I love this module because i pack all userinfo of my website and add it as a single entry to database . here is how :D import struct userid , username , userpassword , verified = 5 , "sun" , "password" , True #my sample datas packeddata = struct.pack("i{0}p{1}p?".format(len(username)+1,len(userpassword)+1) , userid , bytes(username,'utf-8') , bytes(userpassword,'utf-8') , verified ) #here my data is packed , im packing strings as bytes #to unpack it we need to memorize the syntax of packing , here its "i4p9p?" the python official doc has the meaning of #these symballs struct.unpack("i4p9?",packeddata) #will give a tuple of data's we packed now a fun example , we will convert hex color codes to rgb ( R , G , B ) format. ` import struct myhex = 'ff0000' # its red :D cause why not struct.unpack('BBB',bytes.fromhex(myhex)) #will give (255,0,0) cause its red #RGB to hex . yeah (255,0,0) to #ff0000 import struct , codecs rgb = (255,0,0) # again red :D codecs.encode(struct.pack('BBB',*rgb),'hex').decode() #will return "ff0000" have fun with struct module , docs has more of it

6/29/2017 4:42:39 AM


1 Answer

New Answer


grt 👌👌👌