Clear Filters
Clear Filters

evaluating binary substring to decimal value

1 view (last 30 days)
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)
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;
dpb on 9 Aug 2020
function total=EvaluateBinary(substring) --> function unsigned int total=EvaluateBinary(substring)
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;
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.
doc bin2dec
Mohamed Jamal
Mohamed Jamal on 9 Aug 2020
Edited: Mohamed Jamal on 9 Aug 2020
Yes, I just came up from other language of programming (mastering them) and you could say Im newbie in matlab and trying my best.
Appreciated very much

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 9 Aug 2020
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;
if substring(k-1) ~= ' '
counter = counter * 2;
I'm attaching your original question so when you delete it again (like you did with your other question), it will still be available.


Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!