expand_number,
expand_unsigned —
parse a number from human readable
form
System Utilities Library (libutil,
-lutil)
#include
<libutil.h>
int
expand_number(const char *buf,
int64_t *num);
int
expand_unsigned(const char *buf,
uint64_t *num);
The
expand_number()
function parses the number in the string pointed to by its
buf argument and stores the number it represents as a
signed 64-bit quantity in the location pointed to by its
*num argument.
The
expand_unsigned()
function is similar to expand_number(), but accepts
only positive numbers in the range
[0,UINT64_MAX].
Both functions interpret the input “-0” as 0.
The input string must consist of a decimal number, optionally
preceded by a ‘+’ or ‘-’ sign, and optionally
followed, without intervening whitespace, by a suffix indicating a
power-of-two multiplier to apply. Any amount of whitespace at the beginning
of the string will be ignored.
Recognized suffixes are:
| Suffix |
Description |
Multiplier |
K |
kilo |
1,024 |
M |
mega |
1,048,576 |
G |
giga |
1,073,741,824 |
T |
tera |
1,099,511,627,776 |
P |
peta |
1,125,899,906,842,624 |
E |
exa |
1,152,921,504,606,846,976 |
For historical reasons, the
expand_number()
function accepts and ignores a single “B” suffix at the end of
the buf string (i.e. “5b” is interpreted
as 5, and “5kb” is interpreted as 5,120). However, the usage
of this suffix is discouraged.
For backward compatibility reasons, if the
compiler supports generic selection, a macro is provided which automatically
replaces calls to
expand_number()
with calls to expand_unsigned() if the type of the
actual num argument is compatible with
uint64_t *.
Upon successful completion, the value 0 is returned;
otherwise the value -1 is returned and the global variable
errno is set to indicate the error.
The expand_number() and
expand_unsigned() functions will fail if:
- [
EINVAL]
- The given string does not contain a valid number.
- [
EINVAL]
- An unrecognized suffix was encountered.
- [
ERANGE]
- The given string represents a number which does not fit into an
int64_t (for
expand_number()) or uint64_t
(for expand_unsigned()).
The expand_number() function first
appeared in FreeBSD 6.3. The original implementation
did not handle negative numbers correctly, and it was switched to taking a
uint64_t * and accepting only positive numbers in
FreeBSD 9.0. The
expand_unsigned() function was added, and
expand_number() switched back to
int64_t *, in FreeBSD
15.0.