Я преобразовываю числа base-10 в номера base-2 и указывая количество бит, которые я хотел бы использовать для представления этих чисел base-10.Преобразование десятичных двоичных в Matlab?
Вот мой код для отрицательных чисел:
function output = DTB(decimal,binary)
if decimal < 0
smallestNum = -(2^(bits-1));
if decimal < smallestNum
error('%d cannot be represented in %d bits. Increase the number of bits. ',decimal,bits);
output = '';
end
output = '1';
bits = bits - 1;
if smallestNum == decimal
while bits ~= 0
output = [output,'0'];
bits = bits - 1;
end
end
num = smallestNum;
while num ~= decimal
num = smallestNum + 2^(bits-1);
if num > decimal
output = [output,'0'];
else
output = [output,'1'];
smallestNum = smallestNum + 2^(bits-1);
end
bits = bits - 1;
end
while bits ~= 0
output = [output,'0'];
bits = bits - 1;
end
end
Это прекрасно работает. Проблема, с которой я сталкиваюсь (как ни странно, поскольку переход от положительных десятичных дробей к двоичным файлам должен быть проще) с положительными целыми числами. Это должно быть лишь незначительная настройка алгоритма отрицательного числа, верно? Положительный номер не работает в случае decimal
= 8 и bits
= 6, например (он не работает для разных степеней 2). Что здесь не так?
Вот код для положительных целых чисел:
if decimal > 0
largestNum = (2^(bits-1))-1;
if decimal > largestNum
error('%d cannot be represented in %d bits. Increase the number of bits. ',decimal,bits);
output = '';
end
% first spot must be zero to show it's a positive number
output = '0';
bits = bits - 1;
largestNum = largestNum + 1;
num = largestNum;
while num ~= decimal
num = largestNum - 2^(bits-1);
if num > decimal
output = [output,'0'];
end
if num <= decimal
output = [output,'1'];
largestNum = largestNum - 2^(bits-1);
end
bits = bits - 1;
end
while bits ~= 0
output = [output,'0'];
bits = bits - 1;
end
Нет, это очень плохо. 'fi' является частью панели инструментов с фиксированной точкой, которая не подходит для общего решения. Принятое решение не зависит от каких-либо наборов инструментов, поэтому оно наиболее применимо к любому существующему дистрибутиву MATLAB. – rayryeng