Binary to Decimal in Delphi 7

Asked by At

I'm trying to do a simple console program where user input a binary string and he get a decimal number. I dont need to check if the binary string have something else than 0 or 1. I already managed to do decimal to binary but can't do it the other way.

I tried some code found on SO and Reddit but most of the time i got error I/O 105

Here's the dec to bin :

program dectobin;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Crt32;

var
 d,a :Integer;
 str :String;

begin
   str:='';
   Readln(a);
   while a>0 do begin
    d:=a mod 2;
    str:=concat(IntToStr(d),str);
    a:=a div 2;
  end;
  Writeln(str);
  Readln;
end.```

1 Answers

0
Tom Brunberg On Best Solutions

Basics of positional number systems (PNS)

  • The number of unique digits in a PNS is its base (or radix)
    • The decimal system (base = 10) has ten digits, 0..9
    • The binary system (base = 2) has two digits, 0..1
  • The position of a digit in a number determines its weight:
    • the rightmost digit has a weight of units (1), (base)^0 (decimal 1, binary 1)
    • the second (from right) digit has a weight of (base)^1 (decimal 10, binary 2)
    • the third (from right) digit has a weight of (base)^2 (decimal 100, binary 4)
    • and so on ....

Note that the weight is always base * weight of previous digit (in a right to left direction)

General interpretation of a string of numbers in any positional number system

  assign a variable 'result' = 0
  assign a variable 'weight' = 1 (for (base)^0 )
  repeat
    read the rightmost (not yet read) digit from string
    convert digit from character to integer
    multiply it by weight and add to variable 'result'
    multiply weight by base in prep. for next digit
  until no more digits

After previous, you can use e.g. IntToStr() to convert to decimal string.