Binary to decimal converter

조회 수: 28(최근 30일)
mrnice guy
mrnice guy 2020년 4월 8일
댓글: Stephen23 2020년 4월 8일
So, I wrote a program to convert a Binary value to decimal value without using str2num. Here's the code:
dec_val = 0;
base = 1;
bin_val = input('Enter a binary number:');
while bin_val >= 1
rem = mod(bin_val,10);
dec_val = dec_val + (rem * base);
bin_val = round(bin_val / 10);
base = base * 2;
fprintf('decimal value:%d\n',dec_val);
The problem is that when I enter digits greater than 16, the program does not respond. What changes should i make to enter more digits without using bin2dec or str2num?


Guillaume 2020년 4월 8일
"The problem is that when I enter digits greater than 16"
You mean when you enter more than 16 digits?
Indeed your code cannot work properly for numbers with more than 15 digits. The problem is that the user is still entering decimal numbers, not binary. So, if the user enters 100, it's the decimal 100 not the binary 100 (decimal 4). Decimals are stored as double precision floating point numbers which due to the way they're stored can't always be stored accurately. For integer anything above flintmax (~ 9e15) may get rounded. That's about 15 digits of precision. The end result is that if enter 1...(15 x 0)...1, it's going to be stored as 1...(15 x 0)...0
If you want to be able to enter binary numbers with 16 or more digits you can't use double. You could ask for the input as a string (use input(prompt, 's') but of course your code has to change to process characters instead of numbers.
Also note that you never check that the number entered is made of valid digits.
  댓글 수: 3
Stephen23 2020년 4월 8일
You can easily convert the individual digits to numeric:
str = input(...,'s');
vec = str-'0'; % numeric vector of digits
to which you will need to add input checking, etc.

댓글을 달려면 로그인하십시오.


Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by