Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is atoi equivalent for 64bit integer(uint64_t) in C that works on both Unix and Windows?

Tags:

c++

c

atoi

I'm trying to convert 64bit integer string to integer, but I don't know which one to use.

like image 406
JosephH Avatar asked Sep 21 '11 16:09

JosephH


People also ask

What is atoi in C example?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.

What library is atoi in C?

atoi stands for ASCII to integer. It is included in the C standard library header file stdlib.

What does std :: atoi () do?

The atoi() function in C++ is defined in the cstdlib header. It accepts a string parameter that contains integer values and converts the passed string to an integer value.

What is atoi and stoi?

First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.


2 Answers

Use strtoull if you have it or _strtoui64() with visual studio.

unsigned long long strtoull(const char *restrict str,        char **restrict endptr, int base);   /* I am sure MS had a good reason not to name it "strtoull" or  * "_strtoull" at least.  */ unsigned __int64 _strtoui64(    const char *nptr,    char **endptr,    int base  ); 
like image 58
cnicutar Avatar answered Sep 18 '22 08:09

cnicutar


You've tagged this question c++, so I'm assuming you might be interested in C++ solutions too. You can do this using boost::lexical_cast or std::istringstream if boost isn't available to you:

#include <boost/lexical_cast.hpp> #include <sstream> #include <iostream> #include <cstdint> #include <string>  int main() {   uint64_t test;   test = boost::lexical_cast<uint64_t>("594348534879");    // or   std::istringstream ss("48543954385");   if (!(ss >> test))     std::cout << "failed" << std::endl; } 

Both styles work on Windows and Linux (and others).

In C++11 there's also functions that operate on std::string, including std::stoull which you can use:

#include <string>  int main() {   const std::string str="594348534879";   unsigned long long v = std::stoull(str); } 
like image 35
Flexo Avatar answered Sep 19 '22 08:09

Flexo