Skip to content

Instantly share code, notes, and snippets.

@betaEncoder
Last active May 29, 2020 09:08
Show Gist options
  • Save betaEncoder/6ab7b9f98bfc6e2ca44058e10395e8e1 to your computer and use it in GitHub Desktop.
Save betaEncoder/6ab7b9f98bfc6e2ca44058e10395e8e1 to your computer and use it in GitHub Desktop.
interconversion between embedded types and binary
import struct
import ctypes
import array
# 16bit unsigned int to binary
uint16 = 0xff00
raw = array.array("B", struct.pack("<H", uint16)) # "<" means little-endian. ">" means big-endian
print(raw) # array('B', [0, 255])
# multible 16bit unsigned int to binary
uint16_array = array.array("H", [0xff00, 0x55aa])
fmt = "<" + str(len(uint16_array)) + "H"
raw = array.array("B", struct.pack(fmt, *uint16_array)) # "<2H" means little-endian 2 words of uint16
print(raw) # array('B', [0, 255, 170, 85])
# single float to binary
single = 3.14
raw = array.array("B", struct.pack("<f", single))
print(raw) # array('B', [195, 245, 72, 64])
# binary to 32bit int
raw = array.array("B", [0x01, 0x02, 0x03, 0x04])
uint32 = struct.unpack("<L", raw) # struct.unpack() returns tupple
print(uint32[0]) # 67305985 means 0x04030201
# binary to multiple 32bit int
raw = array.array("B", [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08])
fmt = "<" + str(int(len(raw)/ctypes.sizeof(ctypes.c_uint32))) + "L"
uint32 = array.array("L", struct.unpack(fmt, raw))
print(uint32) # array('L', [67305985, 134678021])
# binary to double float
raw = array.array('B', [20, 174, 71, 225, 122, 20, 2, 64])
double = struct.unpack("<d", raw) # struct.unpack() returns tupple
print(double[0]) # 2.26
''' typecode reference
b int8 1byte
B uint8 1byte
h int16 2byte
H uint16 2byte
l int32 4byte
L uint32 4byte
q int64 8byte
Q uint64 8byte
f single float 4byte
d double float 8byte
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment