October 04, 2017

Converting Int/Float ↔ byte stream in python

❑ From a integer/float to a little endian byte stream.
>>> struct.pack("<i", 2000)
'\xd0\x07\x00\x00'
>>> struct.pack("<f", 2000.015)
'{\x00\xfaD'
>>> struct.pack("<f", 2000.5)
'\x00\x10\xfaD'

❑ From a hexadecimal to a little endian byte stream.
>>> struct.pack("<i", 0x7D0)
'\xd0\x07\x00\x00'

❑ From a little endian byte stream to a integer/float.
>>> struct.unpack("<i", "\xd0\x07\x00\x00")
(2000,)
>>> struct.unpack("<f", '{\x00\xfaD')
(2000.0150146484375,)
>>> struct.unpack("<f", '\x00\x10\xfaD')
(2000.5,)


FYI.
import struct or from pwn import *

❑ "python struct module performs conversions between Python values and C structs represented as Python strings. This can be used in handling binary data"

❑ Format string of struct module.