Dezimal in Binär umwandeln in Matlab?
Ich konvertiere Basis-10-Zahlen in Basis-2-Zahlen und gebe die Anzahl der Bits an, die ich zur Darstellung dieser Basis-10-Zahlen verwenden möchte.
Hier ist mein Code für negative Zahlen:
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
Dies funktioniert gut. Das Problem, auf das ich stoße (seltsamerweise, da es einfacher sein sollte, von positiven Dezimalstellen zu binären Zahlen zu wechseln), sind positive ganze Zahlen. Es sollte nur eine geringfügige Änderung des Algorithmus für negative Zahlen sein, oder? Das positive Zahlenstück funktioniert bei @ nicdecimal
= 8 undbits
= 6 zum Beispiel (funktioniert nicht für verschiedene Potenzen von 2). Was ist hier los?
Hier ist der Code für positive ganze Zahlen:
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