Chapter Contents |
Previous |
Next |
strtol |
Portability: | ISO/ANSI C conforming, UNIX compatible |
SYNOPSIS | |
DESCRIPTION | |
RETURN VALUE | |
DIAGNOSTICS | |
EXAMPLE | |
RELATED FUNCTIONS | |
SEE ALSO |
SYNOPSIS |
#include <stdlib.h> long int strtol(const char *str, char **end, int radix);
DESCRIPTION |
strtol
converts a character string to a
long
integer.
The string is expected to contain the representation of an integer in base
radix
. Base
radix
can contain an integer between 2 and 36; if it is larger than 10,
letters 'a' through 'z' (either case) are interpreted as digits greater than
10. If
radix
is 16, a leading 0x may be
present in the string, but it is ignored. Initial white space characters
are always ignored.
If
radix
is 0, the
base is determined by the initial characters of the string (after leading
white space and an optional sign). That is, if the string begins with 0x
or 0X, the base is assumed to be 16; if it begins with 0, it is assumed to
be 8; otherwise, it is assumed to be 10.
If the
end
value
is not
NULL
,
*end
is modified to address the first character of the string that
is not a valid base
radix
digit. However,
if no initial segment of the string can be interpreted as an integer of appropriate
base,
str
is assigned to
*end
.
RETURN VALUE |
strtol
returns the integer value represented by the character string, up to the first
unrecognized character. If no initial segment of the string can be interpreted
as an integer of appropriate base,
0L
is
returned.
DIAGNOSTICS |
If the correct value is too large to be
stored in a 370
long
,
errno
is set to ERANGE and either
LONG_MAX
(231-1) or
LONG_MIN
(-231) is returned, depending
on the sign of the value.
EXAMPLE |
#include <stdlib.h> #include <ctype.h> #include <stdio.h> long int hextol(char *); static int failed; main() { char *string; char input[20]; long output; puts("Enter a hex string to convert to long int:"); string = gets(input); output = hextol(string); if (!failed) printf("The value of the string, printed in decimal, is: %ld\n", output); } long int hextol(char *hexstr) { long value; char *stopchar; /* where strtol conversion stops */ /* Skip space characters. */ while(isspace(*hexstr)) ++hexstr; /* Skip leading 0x. */ if (*hexstr == '0' && tolower(*(hexstr+1)) == 'x') hexstr += 2; /* refused signed hex value */ if (*hexstr == '+' || *hexstr == '-') { puts("Unsigned hex only please"); failed = 1; return -1L; } /* Convert hex to long. */ value = strtol(hexstr, &stopchar, 16); /* Determine whether string is valid. */ if (stopchar == hexstr) { printf("Invalid hex string: %s\n", hexstr); failed = 1; } /* Check for characters after digits. */ else if (*stopchar && !isspace(*stopchar)) printf("Extra characters after hex value ignored: %s\n", stopchar); return value; }
RELATED FUNCTIONS |
SEE ALSO |
Chapter Contents |
Previous |
Next |
Top of Page |
Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.