Integer array to binary array
17,667
Solution 1
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))'
Solution 2
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
Solution 3
A late answer I know, but MATLAB has a function to do this directly de2bi
out = de2bi([3,4,5,6,7], 4, 'left-msb');
Author by
Admin
Updated on June 21, 2022Comments
-
Admin almost 2 years
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?
-
Jonas about 14 yearsI 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.
-
nekomatic over 6 years
de2bi
is only available in the Communications System Toolbox. A similar functiondecimalToBinaryVector
exists in the Data Acquisition Toolbox. -
Shreta Ghimire over 4 yearsDo you have something similar to python?