You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.7 KiB
Python

import struct
import binascii
def get_bin(value, padn=0, sep=None):
"""Prints a binary textual representation of a value in """
return format(value, 'b').zfill(padn)
# Packing a data structure
values = (1, b'ab', 2.7)
s = struct.Struct('I 2s f')
packed_data = s.pack(*values)
print("\n##### Struct Packing Example #####\n\n")
print('Original values :', values)
print('Packed Type :', type(packed_data))
# This is most likely going to contain non ascii characters when printed.
# So it's not suitable to copy it over the printed string and then try to
# hexlify
print('Packed print :', packed_data)
print('Format string :', s.format)
print('Uses :', s.size, 'bytes')
print('Packed Value (hex) :', binascii.hexlify(packed_data))
# binascii.hexlify(data[, sep[, bytes_per_sep=1]]) can also make more
# human readable values
print('Spaced Value (hex) :', binascii.hexlify(packed_data, b"_", 4))
# Unpacking a data structure
packed_data = binascii.unhexlify('0100000061620000cdcc2c40')
unpacked_data = s.unpack(packed_data)
print("\n##### Struct Unpacking Example #####\n\n")
print('Unpacked Values:', unpacked_data)
# Endianness in binary data
print("\n##### Endianness Demonstration #####\n\n")
print('Original values:', values)
endianness = [
('@', 'native, native'),
('=', 'native, standard'),
('<', 'little-endian'),
('>', 'big-endian'),
('!', 'network'),
]
for code, name in endianness:
s = struct.Struct(code + ' I 2s f')
packed_data = s.pack(*values)
print('Format string :', s.format, 'for', name)
print('Uses :', s.size, 'bytes')
print('Packed Value :', binascii.hexlify(packed_data))
print('Unpacked Value :', s.unpack(packed_data), "\n")