1

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)
2
  • Can you check this, pypi.python.org/pypi/bitarray Commented Jul 19, 2013 at 10:52
  • That looks like the wrong tool (meant for interactions with binary files, not conversions within python code), and even if it would do what I want, importing a c-based module seems like a worse solution than what I already have. Commented Jul 19, 2013 at 10:58

2 Answers 2

1

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:]
Sign up to request clarification or add additional context in comments.

3 Comments

this does not exactly do what I want - it is an array of numbers, not booleans. to get the boolean result I want I need to do array([x>0 for x in np.unpackbits(np.array(ord(mychar), dtype=np.uint8))]). And still that's not quite right because it prepends a False to get the uint8 out of ascii's 7 bits.
though i didn't previously know about unpackbits, which looks useful for other problems, so thank you.
ah, thanks. that does look a little cleaner than @tiago 's solution.
0

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?

3 Comments

it's easier for me to read, and gives the right result, so, yes. thank you.
also, the width=4 argument is unnecessary, so np.array(list(np.binary_repr(ord(mychar)))).astype('bool') works
ok, this is closest to my eventual solution, which doesn't use any other numpy functions aside from array itself: np.array(list(bin(ord('d'))))[2:].astype(bool)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.