Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to int64_t?

Tags:

How to convert program parameter from argv to int64_t? atoi() is suitable only for 32 bit integers.

like image 696
pmichna Avatar asked Jun 08 '13 19:06

pmichna


People also ask

How to convert string to Int64 go?

To convert string to int in Golang, use the strconv. ParseInt() method.

How do I convert to Int64?

To convert a Double value to an Int64 value, use the Convert. ToInt64() method. Int64 represents a 64-bit signed integer.

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


2 Answers

A C99 conforming attempt.

[edit] employed @R. correction

// Note: Typical values of SCNd64 include "lld" and "ld". #include <inttypes.h> #include <stdio.h>  int64_t S64(const char *s) {   int64_t i;   char c ;   int scanned = sscanf(s, "%" SCNd64 "%c", &i, &c);   if (scanned == 1) return i;   if (scanned > 1) {     // TBD about extra data found     return i;     }   // TBD failed to scan;     return 0;   }  int main(int argc, char *argv[]) {   if (argc > 1) {     int64_t i = S64(argv[1]);     printf("%" SCNd64 "\n", i);   }   return 0; } 
like image 55
chux - Reinstate Monica Avatar answered Sep 30 '22 20:09

chux - Reinstate Monica


There are a few ways to do it:

  strtoll(str, NULL, 10); 

This is POSIX C99 compliant.

you can also use strtoimax; which has the following prototype:

 strtoimax(const char *str, char **endptr, int base); 

This is nice because it will always work with the local intmax_t ... This is C99 and you need to include <inttypes.h>

like image 20
Ahmed Masud Avatar answered Sep 30 '22 19:09

Ahmed Masud