10

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?

1

3 Answers 3

18

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))'
Sign up to request clarification or add additional context in comments.

1 Comment

Do you have something similar to python?
4

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

1 Comment

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.
1

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');

1 Comment

de2bi is only available in the Communications System Toolbox. A similar function decimalToBinaryVector exists in the Data Acquisition Toolbox.

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.