Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert each element in array to binary python

I have a np array (100,100 dtype=unit8) and I would like to convert each element into binary represented by 8 bits.

I’ve looked over the two questions and answers below, but can’t quite apply them to an n x m array:

Converting integer array to binary array in python

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 a=clip_8bit #clip_8bit is a 100x100 unit8 array
 b=np.zeros_like(a)

for i in a:
    b[i]=bin(int(a[i]))[2:].zfill(8)

IndexError: index 109 is out of bounds for axis 0 with size 100
    

I tried vectorizing and flattening and received either type errors or size-1 array errors

vector = np.vectorize(np.int)
x=clip_8bit_int
x=vector(x)

y=np.zeros_like(x)
y=y.astype(int)
y=vector(y)

for i in y:
    y[i] = bin(i)[2:]  

TypeError: only integer scalar arrays can be converted to a scalar index

How do I convert an array of integers to binary?

This looks to be exactly what I would like to do, but with the issues I had applying the first answer, I’m not understanding exactly how the array is being represented and how the conversion is being applied – here I’m not sure how to extend this code to iterate over an array. I know the following is wrong, but I’ve been going in circles a bit.

int = clip_8bit  #clip_8bit is a 100x100 unit8 array

int maxLen = 0;
for (int i = 0; i < n; i++) {
    bin[i] = Integer.toBinaryString(arr[i]);
    maxLen = Math.max(maxLen, bin[i].length());
}
for (int i = 0; i < n; i++) {
    if (bin[i].length() != maxLen)
        bin[i] = String.format("%" + maxLen + "s", bin[i]).replace(' ', '0');
    System.out.println(bin[i]);
}

Thanks so much, and thanks for your patience with obviously novice questions!

**** edit ****

I did get this working, but the answer below is much better

flat = clip_8bit.flatten()
n = flat.shape[0]
a = flat
b = np.array(np.zeros((n)))

for i in range(n):
    b[i]=bin(int(a[i]))[2:].zfill(8)

c = np.reshape(b, (100, 100), order = 'C')

>Solution :

Numpy has a fast function np.binary_repr() that does what you want for an individual number. You can apply it to an array with np.vectorize():

import numpy as np

l = np.arange(12).reshape([3, 4])
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11]])

np.vectorize(np.binary_repr)(l, 8)
# array([['00000000', '00000001', '00000010', '00000011'],
#        ['00000100', '00000101', '00000110', '00000111'],
#        ['00001000', '00001001', '00001010', '00001011']], dtype='<U8')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading