0

I am working with 64bit hex strings and, when I want to have the number in uint64_t, if the number is higher than 7f... it will not convert the number correct. Since I'm not english, i think i can show the problem better with a piece of code:

   void testing()
   {
      std::string str = "cba321456789654a";
      uint64_t res = std::strtol(str.c_str(), NULL, 16);
      cout << "RESULT " << std::hex << res << endl;
   }

And the result I'm getting is:

RESULT 7fffffffffffffff

Do I have to change the type of my variables to a bigger int? Or there is a way to solve this problem using uit64_t?

2 Answers2

1

You're dealing with unsigned, but are using a string-to-signed conversion routine. And it's not converting to the correct type. strtol converts to a 32-bits long.

 uint64_t res = std::strtol(str.c_str(), NULL, 16);

Should read

 uint64_t res = std::strtoull(str.c_str(), NULL, 16);

Here's a link to c++ string-to-int conversion routines documentation:

http://en.cppreference.com/w/cpp/string/byte/strtoul

Michaël Roy
  • 6,338
  • 1
  • 15
  • 19
1

(Talking about C, because I don't know much about C++. But I assume it still applies to C++.)

strtol() returns an int (which btw isn't 64 bit wide on all platforms). So the domain is (assuming a 64 bit wide int) [INT_MIN, INT_MAX] = [-0x8000000000000000, 0x7fffffffffffffff] and so 0xcba321456789654a cannot be returned.

In POSIX and C99 there is a function strtoull() that should do want you want, i.e. return an unsigned type.

Another alternative is

sscanf("cba321456789654a", "%llx", &res);

.

Uwe Kleine-König
  • 3,426
  • 1
  • 24
  • 20