【发布时间】:2016-03-16 17:01:24
【问题描述】:
我正在将基数为 10 的数字转换为基数为 2 的数字,并指定我想用来表示这些基数为 10 的数字的位数。
这是我的负数代码:
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
【问题讨论】:
标签: matlab function binary decimal