matlab中将负整数十进制转成正整数,matlab - 在Matlab中将十进制转换为二进制? - 堆栈内存溢出...

我正在将以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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值