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

Custom function to convert a decimal integer to binary (upto 20 digits) in MATLAB

我需要编写一个用户定义的 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

四头肌

[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.