Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab binary encoding

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

like image 954
GobiasKoffi Avatar asked Dec 21 '22 21:12

GobiasKoffi


2 Answers

Try:

b = dec2bin(a)
like image 136
Pascal Qyy Avatar answered Dec 24 '22 10:12

Pascal Qyy


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);
like image 37
gnovice Avatar answered Dec 24 '22 09:12

gnovice