67ac010d11267519d2df4730b45657aae104ce8a
[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.2  2005/04/11 18:10:45  bernie
17  *#* Doxygen fixes.
18  *#*
19  *#* Revision 1.1  2005/03/15 00:06:30  bernie
20  *#* Simpler, smaller, faster.
21  *#*
22  *#*/
23
24 #include "strtol10.h"
25
26 /*!
27  * Convert a formatted base-10 ASCII number to unsigned long binary representation.
28  *
29  * Unlike the standard strtoul(), this function has an interface
30  * that makes it better suited for protocol parsers.  It's also
31  * much simpler and smaller than a full featured strtoul().
32  *
33  * \param first  Pointer to first byte of input range (STL-style).
34  * \param last   Pointer to end of input range (STL-style).
35  *               Pass NULL to parse up to the first \\0.
36  * \param val    Pointer to converted value.
37  *
38  * \return true for success, false for failure.
39  *
40  * \see strtol10()
41  */
42 bool strtoul10(const char *first, const char *last, unsigned long *val)
43 {
44         // Check for no input
45         if (*first == '\0')
46                 return false;
47
48         *val = 0;
49         for(/*nop*/; first != last && *first != '\0'; ++first)
50         {
51                 if ((*first < '0') || (*first > '9'))
52                         return false;
53
54                 *val = (*val * 10L) + (*first - '0');
55         }
56
57         return true;
58 }
59
60
61 /*!
62  * Convert a formatted base-10 ASCII number to signed long binary representation.
63  *
64  * \see strtoul10()
65  */
66 bool strtol10(const char *first, const char *last, long *val)
67 {
68         bool negative = false;
69
70         if (*first == '+')
71                 ++first; /* skip unary plus sign */
72         else if (*first == '-')
73         {
74                 negative = true;
75                 ++first;
76         }
77
78         bool result = strtoul10(first, last, (unsigned long *)val);
79
80         if (negative)
81                 *val = - *val;
82
83         return result;
84 }
85