tags:

views:

71

answers:

2

hi, currently in matlab i have int array a=[3,4,5,6,7]; i want to convert it to binary array with four bits each.

for the above int array i would 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? thanks a lot!

+3  A: 

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))'
Jonas
Thanks a lot Jonas!! ;)
asel
+1  A: 

You can use the BITGET function:

abinary = [bitget(a,4); ...  %# Get bit 4 for each number
           bitget(a,3); ...  %# Get bit 3 for each number
           bitget(a,2); ...  %# Get bit 2 for each number
           bitget(a,1)];     %# Get bit 1 for each number
abinary = abinary(:)';      %'# Make it a 1-by-20 array
gnovice
I didn't even know about bitget. I'd make a loop to construct abinary, though, in order to be able to use this for any number of bits. +1 anyway.
Jonas

related questions