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
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
回答 (1 件)
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で MATLAB Compiler についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!