Last active
December 25, 2017 02:52
-
-
Save clarksun/9d354f2b77de520cdadf586c0e2d668d to your computer and use it in GitHub Desktop.
python struct binascii
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://pymotw.com/3/struct/ | |
# struct_pack.py | |
import struct | |
import binascii | |
values = (1, 'ab'.encode('utf-8'), 2.7) | |
s = struct.Struct('I 2s f') | |
packed_data = s.pack(*values) | |
print('Original values:', values) | |
# (1, b'ab', 2.7) | |
print('Format string :', s.format) | |
# b'I 2s f' | |
print('Uses :', s.size, 'bytes') | |
# 12 bytes | |
print('Packed Value :', binascii.hexlify(packed_data)) | |
# b'0100000061620000cdcc2c40' | |
# struct_unpack.py | |
import struct | |
import binascii | |
packed_data = binascii.unhexlify(b'0100000061620000cdcc2c40') | |
s = struct.Struct('I 2s f') | |
unpacked_data = s.unpack(packed_data) | |
print('Unpacked Values:', unpacked_data) | |
# (1, b'ab', 2.700000047683716) | |
# struct_endianness.py | |
import struct | |
import binascii | |
values = (1, 'ab'.encode('utf-8'), 2.7) | |
print('Original values:', values) | |
endianness = [ | |
('@', 'native, native'), | |
('=', 'native, standard'), | |
('<', 'little-endian'), | |
('>', 'big-engian'), | |
('!', 'network'), | |
] | |
for code, name in endianness: | |
s = struct.Struct(code + ' I 2s f') | |
packed_data = s.pack(*values) | |
print() | |
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)) | |
# Byte Order Specifiers for struct | |
# Code Meaning | |
# @ Native order | |
# = Native standard | |
# < little-endian | |
# > big-endian | |
# ! Network order | |
# struct_buffers.py | |
import array | |
import binascii | |
import ctypes | |
import struct | |
s = struct.Struct('I 2s f') | |
values = (1, 'ab'.encode('utf-8'), 2.7) | |
print('Original:', values) | |
print() | |
print('ctypes string buffer') | |
b = ctypes.create_string_buffer(s.size) | |
print('Before :', binascii.hexlify(b.raw)) | |
s.pack_into(b, 0, *values) | |
print('After :', binascii.hexlify(b.raw)) | |
print('Unpacked:', s.unpack_from(b, 0)) | |
print() | |
print('array') | |
a = array.array('b', b'\0' * s.size) | |
print('Before :', binascii.hexlify(a)) | |
s.pack_into(a, 0, *values) | |
print('After :', binascii.hexlify(a)) | |
print('Unpacked:', s.unpack_from(a, 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment