Converting a base ten number into a base two number?

5 ビュー (過去 30 日間)
Alex Wazevich
Alex Wazevich 2019 年 2 月 7 日
コメント済み: Shunichi Kusano 2019 年 2 月 7 日
The number is 47.1875 in base ten, I need to write a script to convert this into base two. So far, I have written for before the decimal place:
x=47;
index=1;
base=2;
q=floor(x/base);
while q>0
q=x/base;
q=floor(q);
r=[rem(x, base)]
result(index)=r;
index=index+1;
x=q;
end
I am having a difficult time with the script for after the decimal place. Any help would be greatly appreciated!

回答 (2 件)

Stephen23
Stephen23 2019 年 2 月 7 日
編集済み: Stephen23 2019 年 2 月 7 日
x = 47.1875;
% Integer part:
n = 1+fix(log2(x));
I = nan(1,n);
y = fix(x);
for k = n:-1:1
I(k) = fix(mod(y,2));
y = fix(y/2);
end
% Fractional part:
n = 12; % places after the radix point.
F = nan(1,n);
y = mod(x,1);
for k = 1:n
F(k) = fix(2*y);
y = mod(2*y,1);
end
% Output:
s = char([I,-2,F]+'0')
giving:
s = 101111.001100000000

Shunichi Kusano
Shunichi Kusano 2019 年 2 月 7 日
編集済み: Shunichi Kusano 2019 年 2 月 7 日
Interesting. Another way to utilize your code. This is a kind of normalization. After calculation, the number of digits is restored.
x_raw = 47.1875;
index=1;
base=2;
n = 12; % places after the radix point.
x = double(x_raw) / double(base)^-n; % normalization
q=floor(x/base);
while q>0
q=x/base;
q=floor(q);
r=[rem(x, base)];
result(index)=floor(r);
index=index+1;
x=q;
end
res2 = reverse(insertAfter(num2str(result,'%1d'), n, '.')) % shifting "." n digits.
hope this helps.
  2 件のコメント
Stephen23
Stephen23 2019 年 2 月 7 日
This code gives the following error:
Undefined function or variable 'x'.
Shunichi Kusano
Shunichi Kusano 2019 年 2 月 7 日
I'm so sorry. I edited the code. Please try again.

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by