poke-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH] add atoi() function (and testsuite)


From: Jose E. Marchesi
Subject: Re: [PATCH] add atoi() function (and testsuite)
Date: Fri, 08 Nov 2019 03:56:47 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/26.1 (gnu/linux)

Hi Michael.

    +/* Convert string to number */
    +
    +defun atoi = (string s, int b = 10) long:
    +  {
    +    defvar result = 0;
    +
    +    defun htoi = (char c) int:
    +      {
    +        if (c >= '0' && c <= '9') return c - '0';
    +        if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    +        if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    +      }
    +
    +    defun valid = (char c, int b) int:
    +      {
    +        if (b <= 10) return (c >= '0') && (c <= '0' + b - 1);
    +        if (b == 16) return ((c >= '0') && (c <= '9')) ||
    +         ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F'));
    +      }
    +
    +    if (!(b in [2, 8, 10, 16]))
    +      raise E_generic;
    +
    +    for (c in s)
    +    {
    +      if (!valid(c, b))
    +        return result;
    +
    +      result = result * b + htoi(c);
    +    }
    +
    +    return result;
    +  }

I just thought about something...  the function as it is works for
numerical prefixes in strings, like in:

(poke) atoi ("132xxx")
132L

But there is no way to know where the parsed number ends within the
string.  In C (strtoll) this is achieved by passing the address of a
pointer that marks the end of the matched number in the passed string.

Maybe we could convey the extra information back to the user...  maybe
returning an array of two numbers: the parsed value, and the position
within the string with the first non-valid character... if that feels
too clumsy maybe it is time to add support for passing arguments by
reference :)

In the meanwhile, I think it would be better to raise an exception when
a "non valid" character is found.

WDYT?



reply via email to

[Prev in Thread] Current Thread [Next in Thread]