摘要:为避免反复编写此类型代码,利用MATLAB编写了将十进制转为二进制(理论可以转为任意进制,不过需要对代码进行维护才能实现),同时支持任意进制转为十进制。
代码如下:
% 本程序用来做进制转换
bit = 4;
L = 10;
xd = 89.8;
lim = [-200, 200];
max_bit = bit.^L - 1; % 该编码下的最大值
[xt] = transformer(xd, lim, max_bit, bit, L);
res = '';
for i = 1:1:L
res = strcat(res, num2str(xt(i)));
end
fprintf('res=%s \n', res)
[xd] = de_trnsformer(xt, lim, max_bit, bit, L);
fprintf('xd=%s \n', xd)
% 十进制转其它进制
function [xt] = transformer(xd, lim, max_bit, bit, L)
scale = lim(2) - lim(1);
X = fix(max_bit * ((xd - lim(1)) / scale));
vessel = zeros(1, L); % 存放进制转换后的结果
for i = 1:1:L
vessel(end-i+1) = mod(X, bit);
X = fix(X/bit);
if X == 0
break
end
end
xt = vessel;
end
% 其它进制转回十进制
function [xd] = de_trnsformer(xt, lim, max_bit, bit, L)
xd = 0;
scale = lim(2) - lim(1);
for i = 1:1:L
xd = xd + xt(end-i+1)*(bit^(i-1));
end
xd = (xd/max_bit) * scale + lim(1);
end