How can I convert a binary fraction to decimal?

20 ビュー (過去 30 日間)
RD
RD 2019 年 6 月 16 日
コメント済み: Jan 2019 年 11 月 28 日
To convert from binary to decimal I use this function: bin2dec('1001')
But how I could like to know how can I convert binary fractions to decimal, just like this: bin2dec('0.110001')

採用された回答

Jan
Jan 2019 年 6 月 16 日
編集済み: Jan 2019 年 11 月 28 日
'11001' means: 1*2^0 + 0*2^1 + 0*2^2 + 1*2^3 + 1*2^4 or:
[1,1,0,0,1] * 2 .^ (4:-1:0).'
(this is what happens inside bin2dec - examine its source code.)
'0.10011' means: 1*2^-1 + 0*2^-2 + 0*2^-3 + 1*2^-4 + 1*2^-5, or:
[1,0,0,1,1] * 2 .^ (-1:-1:-5).'
So all you have to do is to split the part before and after the decimal dot and to convert the character to numbers. Both is easy in Matlab:
S = strsplit('11001.10011', '.');
intV = S{1} - '0';
fracV = S{2} - '0';
intValue = intV * (2 .^ (numel(intV)-1:-1:0).')
fracValue = fracV * (2 .^ -(1:numel(fracV)).')
% or:
sum(fracV ./ (2 .^ (1:numel(fracV))))
% [EDITED] Typo fixed: ^ this was \ before
  3 件のコメント
David K
David K 2019 年 11 月 27 日
This is great, thank you! I think you have a typo in your last code block though. I believe the ldivide on the last line should actually be a rdivide.
Jan
Jan 2019 年 11 月 28 日
Thanks David K. Typo fixed now.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by