evaluating binary substring to decimal value

1 visualización (últimos 30 días)
Mohamed Jamal
Mohamed Jamal el 9 de Ag. de 2020
Respondida: Image Analyst el 9 de Ag. de 2020
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 comentarios
dpb
dpb el 9 de Ag. de 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
Mohamed Jamal
Mohamed Jamal el 9 de Ag. de 2020
Editada: Mohamed Jamal el 9 de Ag. de 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

Iniciar sesión para comentar.

Respuestas (1)

Image Analyst
Image Analyst el 9 de Ag. de 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.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by