Search code examples
pascalfreepascaldelphiturbo-pascal

Change a string to an integer - pascal


I don't know how "xa" can convert in to 10 in pascal. I just use:

Val('xa',value,return);

And value = 10, return = 0. I'm just a newbie, anybody can explain this? I know this won't like the ASCII cause that is just a character.

And I'm using Free Pascal :)

I tested in Free Pascal, when use xa, 0xa and $xa. So, I think it understand the special character like "$","0" without calling it. Is that right?


Solution

  • Since early Delphi's, the core integer conversion routines don't do just number sequences, but also some specials like Pascal "$924" for hex or C style 0x02).

    FreePascal adopted it when it later started adding Delphi compatibility (roughly 1997-2003). Beside this difference, another different is that the last parameter (RETURN in your example) changed from WORD (in Turbo Pascal) to integer/longint in Delphi.

    IOW, the routine accepts the x and thinks you mean to convert a C style hex number, and then interprets the "a" according to Stuart's table.

    It also interprets % as binary, and & as octal.

    Try

    val('$10',value,return);
    writeln(value,' ' ,return);  // 16 0
    val('&10',value,return);
    writeln(value,' ' ,return);  // 8 0
    val('%10',value,return);
    writeln(value,' ' ,return);  // 2 0
    

    and compare the results.

    Note that this probably won't work for very old Pascal's like Turbo Pascal, and Free Pascals from before the year 2000. The % and & are FPC specific to match the literal notation extensions (analogous to $, but for binary and octal)

    var x : Integer
    begin
    x:=%101010;  //42
    x:=&101;     //65