I’m working with a lot of binary data, where my data can be a mix of bit-widths.
I want to print or log my data correctly formatted by bit-width, all in a single statement.
Simple example showing only 16 and 32 bit data:
import numpy as np
numbers_32_bit = np.array((0x1000_0000, 0x2000_0000, 0x3000_0000, 0x4000_0000),dtype=np.uint32)
numbers_16_bit = np.array((0x5000, 0x6000, 0x7000, 0x8000), dtype=np.uint16)
np_formatter = {
# Doesn't throw an error, but has no effect, as expected as per numpy docs
"uint32": lambda x: f"{x:08X}",
"uint16": lambda x: f"{x:04X}",
# Applies to all ints
"int": lambda x: f"0x{x:08X}"
}
np.set_printoptions(formatter=np_formatter)
print(f"32 bits: {numbers_32_bit}, 16 bits: {numbers_16_bit}")
Print output:
32 bits: [0x10000000 0x20000000 0x30000000 0x40000000], 16 bits: [0x00005000 0x00006000 0x00007000 0x00008000]
As you can see, the 16 bit numbers still have the 32-bit formatter applied, as it uses the int
formatter, rather than uint16
.
This works on a statement-by-statement basis, but isn’t great when you have lots of print/log statements throughout a project:
def format_bitwidths(n8=0, n16=0, n32=0, n64=0):
np.set_printoptions(formatter={"int": lambda x: f"0x{x:02X}"})
s8 = f"{n8}"
np.set_printoptions(formatter={"int": lambda x: f"0x{x:04X}"})
s16 = f"{n16}"
np.set_printoptions(formatter={"int": lambda x: f"0x{x:08X}"})
s32 = f"{n32}"
np.set_printoptions(formatter={"int": lambda x: f"0x{x:016X}"})
s64 = f"{n64}"
return s8, s16, s32, s64
_, str_16_bits, str_32_bits, _ = format_bitwidths(n16=numbers_16_bit, n32=numbers_32_bit)
print(f"32 bits: {str_32_bits}, 16 bits: {str_16_bits}")
Print output:
32 bits: [0x10000000 0x20000000 0x30000000 0x40000000], 16 bits: [0x5000 0x6000 0x7000 0x8000]
Is there a way to set this once without having to call np.set_printoptions
or format_bitwidths
before each print/log?
If not, is there some other method which I can set once, and apply it across an entire script?
rici1241 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.