1

I neeed to convert a np array of integers to 12 bit binary numbers, in an array format. What would be the best way to go about doing so?

I've been a bit stuck so any help would be appreciated. Thanks!

Here is what I have to convert an integer to binary:

def dec_to_binary(my_int):
"""

Format a number as binary with leading zeros"""
if my_int < 4096:
    x= "{0:12b}".format(my_int)
    return int(x)
else:
    return 111111111111
4
  • I am able to turn a single integer to binary, but can't figure out how to iterate through the np array and change values without errors: see below - Commented Sep 17, 2016 at 13:37
  • ** See above ** Commented Sep 17, 2016 at 13:37
  • 2
    Just what do you mean by "binary number"? There is no such python object. Commented Sep 17, 2016 at 13:42
  • Why would you want to create an array of 12 bit binary? If this is an attempt to save memory, be aware that solutions involving strings of '1' and '0' actually use much more memory (12 bytes) than 16 bit ints (2 bytes). Commented Sep 17, 2016 at 14:29

1 Answer 1

1

Slight correction (replace 12b with 012b):

def dec_to_binary(my_int):
    """   
    Format a number as binary with leading zeros
    """
    if my_int < 4096:
        return "{0:012b}".format(my_int)
    else:
        return "111111111111"

Example:

In [10]: n_array = np.array([123,234,234,345, 4097])

In [11]: map(dec_to_binary, n_array)
Out[11]: 
['000001111011',
 '000011101010',
 '000011101010',
 '000101011001',
 '111111111111']
Sign up to request clarification or add additional context in comments.

Comments

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.