开发者

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] -开发者_StackOverflow社区-> b=[00000001 00000010 00000011 00000100] --> c=00000001000000100000001100000100


Try:

b = dec2bin(a)


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


Yes, use dec2bin, followed by string concatenation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜