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.

40 lines
1.5 KiB
Python

"""
Module explores the builtins functions for working with some binary data.
"""
import sys
print("This device's native byteorder is: {}\n".format(sys.byteorder))
# One word (16 bit) Hex number
dead_hex = 0xDEAD # 57005
beef_hex = 0xBEEF
print("hex: {} int: {} bin: {} bitlength: {}\n".format(hex(dead_hex), dead_hex, bin(dead_hex), dead_hex.bit_length()))
# Binary numbers
deadbeef_bin = 0xDEADBEEF
print("int.bin_to_bytes type : {}".format(type(deadbeef_bin.to_bytes(4, byteorder="big")))) # immutable type
print("0xDEADBEEF big endian bin : {}".format(deadbeef_bin.to_bytes(4, byteorder="big")))
print("0xDEADBEEF little endian bin : {}".format(deadbeef_bin.to_bytes(4, byteorder="little")))
print("0xDEADBEEF in native endian : {}".format(deadbeef_bin.to_bytes(4, byteorder=sys.byteorder)))
# Error checking in to bytes
try:
deadbeef_bin.to_bytes(1, byteorder=sys.byteorder)
except OverflowError:
print("Caught an overflow error when too few bytes were attempted to represent a 32bit value")
print("Sign matters. Signed binary values use 2's complement.")
value = 0b11111111 # 255 unsigned -1 when signed
bytes_value = value.to_bytes(1, byteorder=sys.byteorder)
print("Unsigned value: {}".format(int.from_bytes(bytes_value, byteorder=sys.byteorder, signed=False)))
print("signed value: {}".format(int.from_bytes(bytes_value, byteorder=sys.byteorder, signed=True)))
## Binascii
# As it says in the standard lib docs this package is for converting binary/ascii