I’m trying to do a simple console program where the user enters a binary string and gets a decimal number in return. I don’t need to check if the binary string contains anything else than 0
s and 1
s. I already managed to do decimal to binary but can’t do it the other way.
I tried some code I found on SO and Reddit but most of the time I get an I/O error (run‑time error 105).
Here’s my decimal to binary implementation:
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.
Basics of positional number systems (PNS)
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.