# Converting string of hex values to numpy array of specific shape

I am working on a project that needs to take a .bdf font file and turn it into a Numpy array. I am using the code below to turn the bitmap for the font into a numpy array. It currently works, I just feel that it's nearly impossible to read but I'm not sure if there's a better way to do it.

How the current code works:

1. It splits the string by line since each line of the string is a row.
2. It selects the first two values from the row since the last two never seem to matter.
3. Using int() I convert the string of hex to an integer.
4. Using bin() I turn the integer to binary.
5. Then I use zfill() because leading zeros in the binary are important. This returns a string of 1's and 0's
6. Then I use list() to break the string of binary into a list of single 1's and 0's
7. Then I convert that all to a numpy array with dtype=int

The process feels really messy and it takes a millisecond which I feel like is pretty long for a (15, 9) numpy array. Any ideas for improvements would be greatly appreciated.

def hexToNumpy(hexValues, columns):

return np.array(
[
list(bin(int(row[0:2], 16))[2:].zfill(columns))
for row in hexValues.split("\n")
],
dtype=int,
)

T = """0000
0000
7F00
0800
0800
0800
0800
0800
0800
0800
0800
0800
0000
0000
0000"""

hexToNumpy(T, 9)


• You can simplify bin(...)[2:].zfill(columns) to f'{...:0>{columns}b}'.

This can use f'{int(row[:2], 16):0>{columns}b}'.

• I'd recommend you convert to a NumPy array out of the function, as it's not really that important to be in there.

• Your code isn't idiomatic, as Python uses snake_case not camelCase.

def from_hex(values, columns):
return [
list(f'{int(row[:2], 16):0>{columns}b}')
for row in values.split("\n")
]