delphifreepascalturbo-pascal

System.Val: String to integer conversion without unambiguous base specification


I don’t understand how xa can be converted to 10 in Borland Pascal. I just use

Val('xa', value, return);

and value becomes 10, and return becomes 0 (meaning successful conversion). I’m just a newbie, can anyone explain this? I know this won’t like the ASCII cause that is just a character.

And I’m using Free Pascal ☺

I tested it in Free Pascal using xa, 0xa and $xa. So, I think Val understands the special characters like $ or 0 without me needing to call specialized functions like Hex2Dec. 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