2

I tried this function to convert a string to _int64 but it didn't work :

_int64 lKey = _atoi64("a1234");

lKey value is always zero and doesn't work except the string is only digits like "1234"

I read solutions using C++ string stream but I want to write my application in pure C

Ahmed
  • 3,398
  • 12
  • 45
  • 64
  • 1
    Remove non-digits first. http://stackoverflow.com/questions/816001/removing-non-integers-from-a-string-in-c – mike jones Oct 31 '11 at 14:26
  • What would you want the function to do on that input? atoi only consumes digits from the front of the string, so any string not beginning with a digit (after leading whitespace) will produce 0. `strtoll` may be more useful to you. – Daniel Fischer Oct 31 '11 at 14:28
  • 1
    Identifiers with underscores usually hint internal usage. If you want to use 64 bit integers you cannot use ansi C, so you probably want to settle on C99 and use strtoll. – Helmut Grohne Oct 31 '11 at 14:30
  • Ok ,I understand that it works fine . But how do I convert a char array to _int64 type ?? – Ahmed Oct 31 '11 at 14:46

2 Answers2

3

The function does indeed work. As the documentation states:

Each function returns the __int64 value produced by interpreting the input characters as a number. The return value is 0 for _atoi64 if the input cannot be converted to a value of that type.

So you have to make sure that a correct string is passed. Otherwise, the return value will always be zero. "a1234" is not a correct string in terms of this function and pretty every "dump" parsing function will fail to parse it.

Constantinius
  • 34,183
  • 8
  • 77
  • 85
2

If you consider your number to be hexadecimal, and C99 is okay, you might want to try strtoull() instead:

const unsigned long long value = strtoull(string, NULL, 16);

Or with auto-detect:

const unsigned long long value = strtoull(string, NULL, 0);
Nicholas Blasgen
  • 772
  • 7
  • 13
unwind
  • 391,730
  • 64
  • 469
  • 606