MATLAB Answers

Binary to decimal converter

176 views (last 30 days)
mrnice guy
mrnice guy on 8 Apr 2020
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;
end
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?

Answers (1)

Guillaume
Guillaume on 8 Apr 2020
"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 Comments
Stephen Cobeldick
Stephen Cobeldick on 8 Apr 2020
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by