0

So I have two hex strings - "3b101c091d53320c000910" and "071d154502010a04000419". When I use strtol() on them I get same value for both strings.

I tried the following code-

    string t1="3b101c091d53320c000910";
    long int hext1=strtol(t1.c_str(),0,16);
    string t2="071d154502010a04000419";
    long int hext2=strtol(t2.c_str(),0,16);
    cout<<hext1<<endl;
    cout<<hext2<<endl;

Both are giving me same value: 9223372036854775807.

I dont know how strtol() works exactly since I am new to C++ but it's giving me same value for two different hex strings. Why?

unwind
  • 391,730
  • 64
  • 469
  • 606
Karlee
  • 9
  • 1
  • The value of these strings is too large to fit within a long int. The value you are getting as a result: 9223372036854775807, is the largest positive value that can fit within a variable of type long int. – Stephen Doyle Sep 22 '14 at 09:52

2 Answers2

5

You should start by reading the manual page. It's returning LONG_MAX since you're input is too large to fit in a long.

Also, strtol() is a very C way of doing things, and you're programming in C++.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • On the other hand, creating an `std::istringstream`, and checking that everything has been consumed, is a pretty heavy solution. I agree that it is probably the one which should be taught first, or at least the one which should be used by a beginner, but `std::strtol` is perfectly valid C++. – James Kanze Sep 22 '14 at 17:01
0

You're not using strtol correctly. You should set errno to 0 before calling it, and check that it is still 0 after; otherwise, it will contain an error code (which can be displayed using strerror). Also, you should pass it the address of a char const*, so that you can ensure that it has processed the entire string (otherwise, "abc" will return 0, without an error):

errno = 0;
char const* end;
long hext1 = strtol( t1.c_str(), &end, 16 );
if ( errno != 0 || *end != '\0' ) {
    //  Error occured.
}
James Kanze
  • 150,581
  • 18
  • 184
  • 329