2

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.

Amir Saniyan
  • 13,014
  • 20
  • 92
  • 137

5 Answers5

3

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.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • 2
    1. The question is tagged C++. 2. Not there on Windows. – Billy ONeal Sep 12 '11 at 13:18
  • Is `stoull` the equivalent to `strtoull` on Windows? – Simon C Sep 12 '11 at 13:21
  • 1. Since he wants to convert a C string, I was assuming a C function would be just fine. 2. That is a problem of course... someone should file a bug report with MS, it's a C99 function. – DarkDust Sep 12 '11 at 13:24
  • @Simon C: Similar, but not the same. – DarkDust Sep 12 '11 at 13:25
  • 1
    MS claims that strtoll is not a C++ function and provides their own extension called `_strtoi64`. – Bo Persson Sep 12 '11 at 13:32
  • @Simon C: stoull is portable, but only defined for C++11. It is similar to strtoull. The main difference is the use of exceptions. – mirk Sep 12 '11 at 13:34
  • I use `strtoll`, `wcstoll`, `strtoull`, `wcstoull` and define these names as a macro in Windows. In windows `_strtoi64`, `_wcstoi64`, `_strtoui64`, `_wcstoui64` are the same functions but different names. – Amir Saniyan Sep 12 '11 at 14:05
3

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;
Jason
  • 31,834
  • 7
  • 59
  • 78
2
long long int i;

if(sscanf(string, "%lld", &i) == 1) { ... }
wormsparty
  • 2,481
  • 19
  • 31
0
 #include <stdlib.h>

 char serial[1000];

 long long var = _atoi64(serial);
borchvm
  • 3,533
  • 16
  • 44
  • 45
0

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188