2015-12-10 3 views
0

Я преобразовываю числа 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 

ответ

2

Вы должны уменьшить большую Num, когда вы положили ноль в выходном массиве, потому что вы, по сути, начиная от двоичного массива всех из них (т.е. largestNum). Этот код работает для меня:

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

вы можете использовать этот скрипт в 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 
+0

Нет, это очень плохо. 'fi' является частью панели инструментов с фиксированной точкой, которая не подходит для общего решения. Принятое решение не зависит от каких-либо наборов инструментов, поэтому оно наиболее применимо к любому существующему дистрибутиву MATLAB. – rayryeng

Смежные вопросы