4

I have a vector containing a series of integers, and what I want to do is take all numbers, convert them into their corresponding binary forms, and concatenate all of the resulting binary values together. Is there any easy way to do this?

e.g. a=[1 2 3 4] --> b=[00000001 00000010 00000011 00000100] --> c=00000001000000100000001100000100

3 Answers 3

4

Try:

b = dec2bin(a)
Sign up to request clarification or add additional context in comments.

Comments

4

As pointed out by the other answers, the function DEC2BIN is one option that you have to solve this problem. However, as pointed out by this other SO question, it can be a very slow option when converting a large number of values.

For a faster solution, you can instead use the function BITGET as follows:

a = [1 2 3 4];               %# Your array of values
nBits = 8;                   %# The number of bits to get for each value
nValues = numel(a);          %# The number of values in a
c = zeros(1,nValues*nBits);  %# Initialize c to an array of zeroes
for iBit = 1:nBits           %# Loop over the bits
  c(iBit:nBits:end) = bitget(a,nBits-iBit+1);  %# Get the bit values
end

The result c will be an array of zeroes and ones. If you want to turn this into a character string, you can use the function CHAR as follows:

c = char(c+48);

Comments

3

Yes, use dec2bin, followed by string concatenation.

Comments

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.