更快的十进制到二进制转换方式

时间:2016-12-19 19:23:06

标签: matlab binary-data

考虑一个整数数组:

X = [1, 3, 3, 3,2,3 ,1,1,2,3]

我想将每个数字转换为4位二进制等价物。我做了以下,但结果不正确。似乎MSB和LSB是相反的。我尝试使用MATLAB&decimal_to_bin =dec2bin(X)的函数,但即使这个输出也是错误的。

我该如何解决这个问题?

X = [1, 3, 3, 3,2,3 ,1,1,2,3];
b = 4;
lookup_table = generate_lookupTable(b);
BinaryX = lookup_table(X,:);



function result = generate_lookupTable(b)

% generate binary code

k = 2^b;
result = zeros(k,b);

for i=1:k
    for j=1:b
        result(i,j) = bitand(uint8(2^(j-1)),uint8(i-1))/uint8(2^(j-1));
    end
end

end

我得到的输出是BinaryX

0   0   0   0
0   1   0   0
0   1   0   0
0   1   0   0
1   0   0   0
0   1   0   0
0   0   0   0
0   0   0   0
1   0   0   0
0   1   0   0

screenshot

1 个答案:

答案 0 :(得分:4)

我认为烧杯意味着以下几点:

% Your vector
X = [1, 3, 3, 3,2,3 ,1,1,2,3];

% number of bits to use 
numbits = 4;

% Create lookup table
little_endian = true;

LUT = dec2bin(0:15, numbits) == '1';
if ~little_endian
    LUT = fliplr(LUT); end

% The conversion 
bits = LUT(X(:) + 1, :)

或者,您可以执行dec2bin所做的事情,但不必大惊小怪:

bits = (rem(floor(X(:)*pow2(1-numbits:0)),2) == 1);