Преобразовать десятичную в двоичную в Matlab?

Я преобразую числа base-10 в числа base-2 и указываю количество бит, которые я хотел бы использовать для представления этих чисел base-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)

Ваш ответ на вопрос