Question

I want to compare two sha1 hashes for equality. What could be the most efficient way to do this? Currently, I am trying using memcmp. Thanks.

Was it helpful?

Solution

Well, since you already know at compile-time how large the blocks are, you could do this:

#include <cstdint>

bool is_same_sha1(const char* p, const char* q)
{
    const std::uint32_t* a = (const std::uint32_t*)p;
    const std::uint32_t* b = (const std::uint32_t*)q;
    return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]
        && a[3] == b[3] && a[4] == b[4];
}

But don't take my advice blindly, you should measure any custom solution against the memcmp solution and only use it if it gives you a significant performance advantage. I wouldn't even be surprised if memcmp was still faster because it did something extremely clever and dirty.

OTHER TIPS

What's wrong with memcmp()? You have to compare every byte of both hashes; memcmp() will quickly fail on the first difference it finds; and memcmp() can be written by the library authors to work in chunk sizes that are good choices for the platform.

std::equal would seem the best bet, but memcmp would also work. With regards to efficiency, it will depend on the implementation, but also (possibly) how the data is defined and represented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top