Filter löschen
Filter löschen

Binary to decimal converter

48 Ansichten (letzte 30 Tage)
mrnice guy
mrnice guy am 8 Apr. 2020
Kommentiert: Stephen23 am 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?

Antworten (1)

Guillaume
Guillaume am 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 Kommentare
Guillaume
Guillaume am 8 Apr. 2020
If you want the user to be able to enter more than 15 binary digits you have to use input(prompt, 's') but you must not convert to number (with str2num, str2double or others). You must keep it as text otherwise you're back to the same problem that as a number you're going to get rounding.
Your current while loop can easily be adapted to work with characters. At the moment, you've got an implicit expectations that the digits are 0 or 1, you can easily change that so you have an explicit expectation that the digits are the characters '0' or '1'. You could even convert the while loop to a for loop.
Stephen23
Stephen23 am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by