Simpler, smaller, faster.
[bertos.git] / mware / strtol10.c
1 /*!
2  * \file
3  * <!--
4  * Copyright 2005 Develer S.r.l. (http://www.develer.com/)
5  * This file is part of DevLib - See README.devlib for information.
6  * -->
7  *
8  * \brief Poor man's hex arrays (implementation).
9  *
10  * \version $Id$
11  * \author Bernardo Innocenti <bernie@develer.com>
12  */
13
14 /*#*
15  *#* $Log$
16  *#* Revision 1.1  2005/03/15 00:06:30  bernie
17  *#* Simpler, smaller, faster.
18  *#*
19  *#*/
20
21 #include "strtol10.h"
22
23 /*!
24  * Convert a formatted base-10 ASCII number to unsigned long binary representation.
25  *
26  * Unlike the standard strtoul(), this function has an interface
27  * that makes it better suited for protocol parsers.  It's also
28  * much simpler and smaller than a full featured strtoul().
29  *
30  * \param first  Pointer to first byte of input range (STL-style).
31  * \param last   Pointer to end of input range (STL-style).
32  *               Pass NULL to parse up to the first \0.
33  * \param val    Pointer to converted value.
34  *
35  * \return true for success, false for failure.
36  *
37  * \see strtol10()
38  */
39 bool strtoul10(const char *first, const char *last, unsigned long *val)
40 {
41         // Check for no input
42         if (*first == '\0')
43                 return false;
44
45         *val = 0;
46         for(/*nop*/; first != last && *first != '\0'; ++first)
47         {
48                 if ((*first < '0') || (*first > '9'))
49                         return false;
50
51                 *val = (*val * 10L) + (*first - '0');
52         }
53
54         return true;
55 }
56
57
58 /*!
59  * Convert a formatted base-10 ASCII number to signed long binary representation.
60  *
61  * \see strtoul10()
62  */
63 bool strtol10(const char *first, const char *last, long *val)
64 {
65         bool negative = false;
66
67         if (*first == '+')
68                 ++first; /* skip unary plus sign */
69         else if (*first == '-')
70         {
71                 negative = true;
72                 ++first;
73         }
74
75         bool result = strtoul10(first, last, (unsigned long *)val);
76
77         if (negative)
78                 *val = - *val;
79
80         return result;
81 }
82