Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer array to binary array

I have an integer array:

a=[3,4,5,6,7];

I want to convert it to a binary array with four bits each. For the above integer array I would like get the following binary array:

abinary=[0,0,1,1, 0,1,0,0, 0,1,0,1, 0,1,1,0, 0,1,1,1];

Is there any fast way to do it?

like image 385
asel Avatar asked Apr 22 '10 01:04

asel


1 Answers

Matlab has the built-in function DEC2BIN. It creates a character array, but it's easy to turn that back to numbers.

%# create binary string - the 4 forces at least 4 bits
bstr = dec2bin([3,4,5,6,7],4)

%# convert back to numbers (reshape so that zeros are preserved)
out = str2num(reshape(bstr',[],1))'
like image 158
Jonas Avatar answered Oct 12 '22 02:10

Jonas