evaluating binary substring to decimal value

1 次查看(过去 30 天)
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 个评论
dpb
dpb 2020-8-9
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
Mohamed Jamal
Mohamed Jamal 2020-8-9
编辑:Mohamed Jamal 2020-8-9
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

请先登录,再进行评论。

回答(1 个)

Image Analyst
Image Analyst 2020-8-9
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.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by