Search code examples
procedurepascal

Pascal: Val() function is returning negative number


I've been trying to convert a string into an integer and val() procedure is returning a negative number, I thought it was becouse the string was too large (doesn't make sense, the length of the string is about 8), so I tried making the conversion manually and it returns exactly the same number val() is returning:

program a;
uses crt;

var
    text:string;
    number, code:integer;

begin
    number:=0;
    
    text := '3142436';
    val(text, number, code);
    
    writeln('Number: ', number);
    writeln('Code: ', code);
    
    
end.

And it returns:

Number: -3292
Code: 0

Making my own conversion procedure:

program a;
uses crt;

var
    numero, cod:integer;
    info:string;
    i:char;

begin
    cod:=0;
    numero:=0;
    info:='3142436';

    for i in info do
        begin
            case i of
                '0': cod:= 0;
                '1': cod:= 1;
                '2': cod:= 2;
                '3': cod:= 3;
                '4': cod:= 4;
                '5': cod:= 5;
                '6': cod:= 6;
                '7': cod:= 7;
                '8': cod:= 8;
                '9': cod:= 9;
            end;
            numero := (numero * 10) + cod;
            write('Now: ', numero);
            writeln(' (Adding ',cod, ')');
        end;
    
    writeln('Result: ', numero);
    
end.

Returns exactly the same:

Now: 3 (Adding 3)
Now: 31 (Adding 1)
Now: 314 (Adding 4)
Now: 3142 (Adding 2)
Now: 31424 (Adding 4)
Now: -13437 (Adding 3)
Now: -3292 (Adding 6)
Result: -3292

Is there something i'm doing wrong?


Solution

  • You are clearly using a 16-bit integer type.

    3142436 is $2FF324 which truncated to a word is $F324. Interpreted as a signed integer, this is -3292 in decimal.

    There are many Pascal implementations. You didn't specify which one you are using, but apparently Integer is a 16-bit integer with your current compiler settings.