How to cross-platform converting char* to long long (64-bit)?
-
29-10-2019 - |
문제
How can I convert a char* string to long long (64-bit) integer?
I use MSVC and GCC compilers and my platforms are Windows, Linux and MAC OS.
Thanks.
해결책
Use strtoull
for unsigned long long or strtoll
for signed long long. On any Unix (Linux, Mac OS X), type man strtoull
or man strtoll
to get its description. Since both are part of the C99 standard they should be available on any system that supports C. The Linux man pages also have examples on how to use them.
다른 팁
For C++ with a compiler that supports long long int
, I would use a std::istringstream
object. For instance:
char* number_string;
//...code that initializes number_string
std::istringstream input_stream(number_string);
long long int i64_bit_type;
input_stream >> i64_bit_type;
long long int i;
if(sscanf(string, "%lld", &i) == 1) { ... }
boost::lexical_cast
is probably the simplest (in code). See http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm for more info. Alternately use a stringstream
to parse out the numeric value.
#include <stdlib.h>
char serial[1000];
long long var = _atoi64(serial);