Converting base 10 to base 2, dec2base help

36 ビュー (過去 30 日間)
Jarred
Jarred 2014 年 2 月 13 日
編集済み: Walter Roberson 2021 年 11 月 21 日
So I am writing a script to convert a number from base 10 to base 2. I have written my own script, but I had trouble using dec2base. The function does not seem to work when I write something like
(i = dec2base(4, 2); and also fprintf('%g', i))
It outputs 494848. However, if I simply write dec2base(4, 2) without a semicolon the operation works, but the format is wrong.

採用された回答

Jos (10584)
Jos (10584) 2014 年 2 月 13 日
X = dec2base(4,2)
whos X % X is a character array!
fprintf('%g', X) % prints out ascii codes of the string!, Similar to ...
fprintf('%g', 'hello')
fprintf('%s', X) % use %s as a format string for character arrays
  1 件のコメント
Jarred
Jarred 2014 年 2 月 13 日
Simply and concise!

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2014 年 2 月 13 日
bits_wanted = 16;
i = dec2base(4, 2, bits_wanted);
fprintf(i);

Sagar Damle
Sagar Damle 2014 年 2 月 13 日
編集済み: Walter Roberson 2021 年 11 月 21 日
In MATLAB, either a comma(,) or a semi colon(;) separates two statements. Semi colon doesn't print the answer.
I think,you will require a 'number' in base 2 format and not a 'string'(i.e. character array).There are many functions in MATLAB to convert base 10 to base 2 of a number –
1. dec2base()
2. dec2bin()
3. de2bi()
4. dec2binvec()
However,outputs of these are are not in same format. Run this code on your computer for understaning purpose. See help about these functions in MATLAB.
Note : '0' represents ASCII value of zero(0) which is 48. So,
ans2 = dec2base(4,2) - '0'
is same as
ans2 = dec2base(4,2) – 48
Play with these functions! ENJOY!
% Program -
temp1 = dec2base(4,2)
ans1 = str2num(dec2base(4,2))
ans2 = dec2base(4,2) - '0'
temp2 = dec2bin(4)
ans3 = dec2bin(4) - '0'
temp3 = de2bi(4)
temp4 = de2bi(4,'right-msb')
ans4 = de2bi(4,'left-msb')
temp5 = dec2binvec(4)
ans5 = seqreverse(dec2binvec(4))
whos

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by