在MATLAB中将十进制整数转换为二进制(最多20位)的自定义函数



我需要编写一个用户定义的MATLAB函数,将以二进制形式编写的整数转换为十进制形式。将函数命名为d=binaTOint(b),其中输入参数b是一个具有1和0的向量,表示要转换的二进制数,输出参数d是一个十进制数字。可以用该函数转换的最大数字应该是20个1的二进制数。如果为b输入了一个较大的数字,则函数应显示一条错误消息。

这应该为您完成:

function result = binaToInt(number)
% Assuming that the system is a little endian i.e.
% LSB is on the right
if ~(all(number>=0) && all(number<=1))
    error('Only 0s and 1s are allowed');
elseif length(number) > 20
    error('Maximum 20 digits allowed');
end
number = int32(number); % Convert the types appropriately
result = 0; % Pre allocate 0 (that's the minimum anyway)
% Loop through numbers;
n = length(number);
for i = 1:n
    result = result + (number(i)*(2^(n-i)));
end

Tets

[0 0 0 0 1 0 1 0] gives out 10
[1 1] gives out 3
[0 0 0 0 0 1 1 1] gives out 7
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] gives out 1048575
[0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] gives out error because only 20 digits are allowed.

请记住,在这种情况下使用2s补码算法非常有用如果您真的想使用2s完成,所需的修改将是:

Force users to enter 20 digits where the MSB 1 means negative, 0 means positive
and you need to do the maths accordingly (i.e. subtract/add the MSB with the rest of the digits when accumulating the sum.

最新更新