persephani
persephani

Reputation: 13

python: convert ascii character to boolean array

I have a character. I want to represent its ascii value as a numpy array of booleans. This works, but seems contorted. Is there a better way?

bin_str = bin(ord(mychar))
bool_array = array([int(x)>0 for x in list(bin_str[2:])], dtype=bool)

for

mychar = 'd'

the desired resulting value for bool_array is

array([ True,  True, False, False,  True, False, False], dtype=bool)

Upvotes: 1

Views: 1201

Answers (2)

Jaime
Jaime

Reputation: 67507

You can extract the bits from a uint8 array directly using np.unpackbits:

np.unpackbits(np.array(ord(mychar), dtype=np.uint8))

EDIT: To get only the 7 relevant bits in a boolean array:

np.unpackbits(np.array(ord(mychar), dtype=np.uint8)).astype(bool)[1:]

Upvotes: 1

tiago
tiago

Reputation: 23502

This is more or less the same thing:

>>> import numpy as np
>>> mychar = 'd'
>>> np.array(list(np.binary_repr(ord(mychar), width=4))).astype('bool')
array([ True,  True, False, False,  True, False, False], dtype=bool)

Is it less contorted?

Upvotes: 0

Related Questions