Welcome, Guest. Please login or register.

Author Topic: itoa && ltoa in VBCC  (Read 2269 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: itoa && ltoa in VBCC
« on: September 09, 2005, 10:11:41 PM »
Quote
Code: [Select]
long atol (char *s)

{
long i = 0;

while (*s >= '0' && *s <= '9')
        {
        i = (i * 10) + (*s - '0');
        s ++;
        }

return (i);
}

And a working version:
Code: [Select]

#include
#include
#include

long atol(char *s)
{
    int sign = 1;
    long i = 0, ni;

    while (isblank(*s))
    {
        s++;
    }

    if (*s == '+')
    {
        s++;
    }
    else if (*s == '-')
    {
        sign = -1;
        s++;
    }

    while (*s >= '0' && *s <= '9')
    {
        ni = (i * 10) + (*s - '0');
        if (ni < i)
        {
            errno = ERANGE;
            return sign > 0 ? LONG_MAX : LONG_MIN;
        }
        i = ni;
        s++;
    }

    return sign * i;
}

 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: itoa && ltoa in VBCC
« Reply #1 on: September 09, 2005, 10:25:06 PM »
Quote
itoa && ltoa

I noticed vbcc's stdlib.h doesn't inlcude these.

...and for a reason, those are not ANSI C functions.

What do they do anyway?

[EDIT]
Ahh, ok, google is your friend.

Code: [Select]
// maximum string buffer needed, plus one for a minus sign when negative

#define MAX_LENGTH 32+1

char* ltoa(char* buf, long i, int base)
{
    char reverse[MAX_LENGTH+1]; // plus one for the null
    char* s;
    char sign = i < 0;

    i = labs(i);
    reverse[MAX_LENGTH] = 0;
    s = reverse+MAX_LENGTH;
    do {
        *--s = &quot;0123456789abcdefghijklmnopqrstuvwxyz&quot;[i % base];
        i /= base;
    } while (i);
    if (sign) *--s = '-';
    return strcpy(buf, s);
}


(From the abovementioned post by John Passaniti)
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: itoa && ltoa in VBCC
« Reply #2 on: September 25, 2005, 03:17:22 AM »
@Wain
Quote
Am I reading that right? Does the above code support up to base 36?


It sure does. Apparently there are different kinds of implementations of the function (it's non-std after all).

This one looks quite complete. Check the discussion in the google link of my previous post.

[oops, the link was broken, fixed now..]
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: itoa && ltoa in VBCC
« Reply #3 on: September 25, 2005, 03:20:10 AM »
@vic20owner

Yeah well, but that only covers base == 10 case.