在Matlab中将十进制转换为二进制?

时间:2015-12-10 21:50:24

标签: matlab function binary decimal

我正在将基数为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

2 个答案:

答案 0 :(得分:2)

当您在输出数组中放置零时,需要减少最大数量,因为您实际上是从所有1的二进制数组(即maximumNum)开始。这段代码对我有用:

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'];
        largestNum = largestNum - 2^(bits-1);
    end
    if num <= decimal
        output = [output,'1'];

    end
    bits = bits - 1;
end

while bits ~= 0
    output = [output,'0'];
    bits = bits - 1;
end
end

我不确定这是为了什么,但我强烈建议使用内置的dec2bin来执行此操作。

答案 1 :(得分:-1)

你可以在matlab中使用这个脚本:

a=[1 2 3 4;-2 -4 3 4;7 8 9 4];

[c,v]=size(a);

n3=c*v;

word_len=5;%with bits of binary  word

data = reshape(a', n3, 1);

databin= fi(data,1,5);

h=bin(databin)%result