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.

2
  • So… convert to an unsigned integer, which has the full positive range your strings have? (Never mind why you’re getting a string-valued hash, which must have been converted from integers already…) Jan 14, 2020 at 0:51
  • key.dwFirst = std::stoul(strHash.substr(0, 8), nullptr, 16); . You can use the base argument for stoul or strtoul instead of prepending 0x
    – M.M
    Jan 14, 2020 at 2:08

1 Answer 1

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.

2
  • Wow. Thanks! That was fast. Any suggestion on the function that I can use to convert the string to DWORD?
    – vaska11
    Jan 14, 2020 at 0:59
  • Nevermind, I used istringsteam to solve the problem. Thanks for the help.
    – vaska11
    Jan 14, 2020 at 1:10

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.