Printing out DWORD in hex returns 0x7FFFFFFF in win32 c++

0

I'm currently working on win32 application that uses sha1 hash on strings to generate keys for my map. I want to use the hash as DWORD, so I can compute some calculations between hashes.

Since sha1 hash reproduces 160-bit hash values, I created a struct with 5 DWORD (32-bit * 5 = 160).

struct _SHA1_HASH
{
   DWORD dwFirst;
   DWORD dwSecond;
   DWORD dwThird;
   DWORD dwFourth;
   DWORD dwFifth;
}SHA1_HASH;

And I have hashed the string and stored into the struct.

void GenerateNodeKey()
{
    // SHA-1 Hashing Process
    // ex) strHash = 356A192B7913B04C54574D18C28D46E6395428AB    

    SHA1_HASH key;
    string s_prefix = "0x";
    key.dwFirst = strtol((s_prefix+strHash.substr(0,8)).c_str(), 0, 0); // first 8 bytes
    ...
    ...
    key.dwFifth = strtol((s_prefix+strHash.substr(32,8)).c_str(), 0, 0); // last 8 bytes
}

But the problem arose when I try to print the value to check if they are alright.

    wcout << hex 
          << "Node ID : " << key.dwFirst << key.dwSecond << key.dwThird << key.dwFourth << key.dwFifth 
          << dec
          << endl;

It prints out with no problems if the 8-byte hex value is less than 7FFFFFFF (2,147,483,647). However, when it is larger than the value, it just prints out the max number. I searched online to see if how large can DWORD hold, and that was no problem (Related : What is the largest integer number base 16 that can be store in a variable of type dword?)

Can somebody help? Thanks in advance.

c++
winapi
dword
asked on Stack Overflow Jan 14, 2020 by vaska11

1 Answer

2

The strtol function returns a signed long integer, which on windows has a range of -2,147,483,648 to 2,147,483,647.

If strtol detects that the number generated is out of range, it will return the maximum long value. From cppreference:

If the converted value falls out of range of corresponding return type, a range error occurs (setting errno to ERANGE) and LONG_MAX, LONG_MIN, LLONG_MAX or LLONG_MIN is returned.

Use std::strtoul instead.

answered on Stack Overflow Jan 14, 2020 by zdan

User contributions licensed under CC BY-SA 3.0