开发者

is strtoul not endian safe?

So I am doing a conversion from a string to an unsigned long using strtoul on both a little endian and big endian machine. The little endian machine returns the correct value, while the big endian machine does not. Is this function truly not compatible on big endian machines? If so, is there a work around?

Code:

printf ("%s\n",cLongs);
theLongs[i] = strtoul(cLongs, NULL, 10);
cout << "returned unsigned long value from string: " << theLongs[i] << endl;

Little endian result:

1099188638048931
returned unsigned long value from string: 1099188638048931
开发者_Python百科

Big endian result:

1099188638048931
returned unsigned long value from string: 4294967295

P.S. It appears that the same number is always returned for the Big endian example.


strtoul returns ULONG_MAX on overflow. That's what you are hitting. I'm assuming one is running on 32bit the other on 64bit on top of the Endianess differences. 4294967295 == 0xFFFFFFFF, which for a 32bit machine would be ULONG_MAX.


Try whether the following works for you on both systems. I could only test it on a 64bit Little Endian Linux so far. If so, you can use string streams for conversion (which is anyway the C++ style to do things):

#include <iostream>
#include <sstream>

int main()
{
  using namespace std;
  string sval("1099188638048931"); // your huge value, exceeding 32bit
  istringstream sst(sval); // assign string to a stream
  unsigned long long myval;
  sst >> myval; // convert stream to unsigned 64bit integer
  cout << myval << endl; // output the converted result
  return 0;
}

Note, that unsigned long long would have to be unsigned __int64 with MSVC. Other compilers may have again other names. If you are lucky you'll have standard types on all your platforms and can use uint64_t ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜