Explain this MATLAB code to me? Trying to convert binary to decimal (where bin_n
ID: 656067 • Letter: E
Question
Explain this MATLAB code to me? Trying to convert binary to decimal (where bin_num is an input that is a string). I sort of understand what it's doing. (this isn't the full code, just the portion I don't understand)
bin_num=bin_num-'0'; %I'm not sure what this is doing... is this checking for 0's???
dec=0;
PNT=0;
for i1=1:length(bin_num)
if(bin_num(i1)<0)
PNT=i1; %what is the signficance of PNT??? I don't understand why we need this for loop, besides %checking if the string is empty
break;
end
dec(i1)=bin_num(i1);
end
deci=sum(dec.*(2.^(length(dec)-1:-1:0))); %what is dec referring to? and does the middle '-1' mean we %start at the opposite end of the string?
deci_val=deci
Explanation / Answer
The line,
bin_num=bin_num-'0';
will means that this string will start from '0' onwards.
The 'for' loop is used to parse entire string of binary value and whenver bin_num digit value is less than 0 then PNT variable will be assigned to that value.
In the line,
deci=sum(dec.*(2.^(length(dec)-1:-1:0)));
'dec' is the declared variable that tracks the current binary value and -1 refer to the sign.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.