evaluating binary substring to decimal value
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi guys, Im implementing a function that gets in its input binary substring of 8bit like this '00000001' and outputs the unsigned integer value of the given input. (output is a variable total, in my example above the retunred value is 1 because 2^0 in binary is '00000001')
I've done in matlab a function like this but it doesn't work well and I get a compilation error and I dont know why:
function unsigned int total=EvaluateBinary(substring)
byteSize=8;
char retChar = '\0';
uint8_t total = 0; %this varibal is unsigned integer of 8bit
int counter = 1;
for int i=byteSize:i>0:--i
if (substring(i-1) == '1') total += counter;
if (substring(i-1) ~= ' ') counter *= 2;
return total;
end
2 Kommentare
dpb
am 9 Aug. 2020
function total=EvaluateBinary(substring) --> function unsigned int total=EvaluateBinary(substring)
byteSize=8;
retChar = '\0';
uint8_t total = uint8(0); %this varibal is unsigned integer of 8bit
counter = uint8(1);
for i=byteSize:-1:1
if (substring(i-1) == '1'), total += counter; end
if (substring(i-1) ~= ' '),
counter *= 2;
return total;
end
end
end
MATLAB is not C; it is untyped; you cast to a given type, you don't declare a variable as being of a given type.
for and if ... end constructs have MATLAB syntax construction that doesn't identically match C, either.
Read the documentation for basic syntax getting started section.
But, for the particular problem, just use the builtin bin2dec function.
See
doc bin2dec
Antworten (1)
Image Analyst
am 9 Aug. 2020
Mohamed:
That code, which is part C and part MATLAB, would be this in MATLAB:
function total=EvaluateBinary(substring)
byteSize = 8;
retChar = '\0';
total = uint8(0); % This variable is unsigned integer of 8 bit
counter = 1;
for k = byteSize : -1 : 0
if substring(k-1) == '1'
total = total + counter;
end
if substring(k-1) ~= ' '
counter = counter * 2;
end
end
I'm attaching your original question so when you delete it again (like you did with your other question), it will still be available.
0 Kommentare
Siehe auch
Kategorien
Mehr zu MATLAB Compiler finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!