Skip to content

Instantly share code, notes, and snippets.

@leiless
Last active August 4, 2019 00:51
Show Gist options
  • Save leiless/efe6b43737c97782382f395cd68cea1c to your computer and use it in GitHub Desktop.
Save leiless/efe6b43737c97782382f395cd68cea1c to your computer and use it in GitHub Desktop.
[sic strtol(3)] Convert a string value to a long long
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
/**
* [sic strtoll(3)] Convert a string value to a long long
*
* @str the value string
* @delim delimiter character(an invalid one) for a success match
* note '\0' for a strict match
* other value indicate a substring conversion
* @base numeric base
* @val where to store parsed long value
* @return 1 if parsed successfully 0 o.w.
*
* @see: https://stackoverflow.com/a/14176593/10725426
*/
int parse_long_long(const char *str, char delim, int base, long long *val)
{
int ok;
char *p;
long long t;
errno = 0;
t = strtoll(str, &p, base);
ok = errno == 0 && *p == delim;
if (ok) *val = t;
return ok;
}
/**
* [sic strtoll(3)] Convert a string value to a long
* @see: parse_long_long()
*/
int parse_long(const char *str, char delim, int base, long *val)
{
long long t;
int ok;
ok = parse_long_long(str, delim, base, &t) &&
(t & ~((unsigned long long) ULONG_MAX)) == 0;
if (ok) *val = t;
return ok;
}
@leiless
Copy link
Author

leiless commented Aug 4, 2019

NOTE: You can rename parse_long_long to parse_llong

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment