Converting binary to decimal and vice versa, please help!!
Afficher commentaires plus anciens
I'm having trouble converting strings that represent binary numbers to decimal and vice versa. The main issue is that I'm unsure of how to deal with the decimal point, say converting -11.11 to decimal. This is a homework assignment, so I'm not allowed to use the built in functions.
Here's my code for one of the two:
function decimal= mybin2real(binarystring)
decimal = 0;
for i = 1 : length(binarystring)
decimal = decimal + str2num(binarystring(i)) * 2^(length(binarystring) - i);
end
decimal
end
I was thinking about finding where the decimal point was using strfind, but i'm not sure how to implement it in the matlab code.
6 commentaires
Daniel Shub
le 2 Nov 2012
Modifié(e) : Daniel Shub
le 2 Nov 2012
You realize that your example code is littered with built in functions. As bin2dec is not a builtin function, why not just use it. Or maybe retype the function yourself. Have you looked at how bin2dec solves the problem?
SB
le 2 Nov 2012
Daniel Shub
le 2 Nov 2012
I will repeat myself: Have you looked at how bin2dec solves the problem. In general the code included in MATLAB is of pretty high quality.
SB
le 2 Nov 2012
Daniel Shub
le 2 Nov 2012
At the command line type
type bin2dec
or
edit bin2dec
this will let you see the source code.
SB
le 2 Nov 2012
Réponse acceptée
Plus de réponses (2)
Andrei Bobrov
le 2 Nov 2012
Modifié(e) : Andrei Bobrov
le 3 Nov 2012
decimal = (binarystring-'0')*pow2(size(binarystring,2)-1:-1:0).';
ADD
binarystring = '-11.11';
b = binarystring - '0';
[~,s] = ismember([-3,-2],b);
p = b(b >= 0);
decimal = sign(b(1))*p*pow2(diff(s) + (-2:-1:-1-numel(p)))';
prince kumar
le 15 Juil 2018
Modifié(e) : KSSV
le 23 Oct 2019
n=input('input binary no.=');
n=int2str(n); s=0;
for i=1:numel(n)
s=s+(str2num(n(i))*(2.^(numel(n)-i)));
end
s
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!