Binary coding matlab

I have a vector containing a series of integers, and I want to make all the numbers, convert them to the corresponding binary forms, and combine all the resulting binary values ​​together. Is there an easy way to do this?

eg. a = [1 2 3 4] β†’ b = [00000001 00000010 00000011 00000100] β†’ c = 00000001000000100000001100000100

+4
source share
3 answers

Try:

b = dec2bin(a) 
+4
source

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

For a faster solution, you can instead use the BITGET function 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 of c will be an array of zeros and ones. If you want to turn this into a character string, you can use the CHAR function as follows:

 c = char(c+48); 
+4
source

Yes, use dec2bin followed by string concatenation.

+3
source

All Articles