poke-devel
[Top][All Lists]

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

 From: Michael Drüing Subject: Re: Re: [PATCH] add atoi() function (and testsuite) Date: Sat, 9 Nov 2019 18:32:59 +0100

Hi,

I tried to model the behavior of atoi() as close as possible to the C version of atoi(), which stops at the first non-digit number. I think atoi() should be as simple and straightforward to use as possible, same as in C.
We can add a strtoll() function later that does what the C strtoll() function does.

No need to make it any more confusing for people who know C :-)

-Michael
--
Sent from my Android phone with GMX Mail. Please excuse my brevity.
On 11/8/19, 03:56 "Jose E. Marchesi" <address@hidden> wrote:

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?