I have a function that computes the checkLeadingZeroBits as follows:
typedef std::array<uint8_t, 32> SHA256Hash; bool checkLeadingZeroBits(SHA256Hash& hash, unsigned int challengeSize) { int bytes = challengeSize / 8; const uint8_t * a = hash.data(); if (bytes == 0) { return a[0]>>(8-challengeSize) == 0; } else { for (int i = 0; i < bytes; i++) { if (a[i] != 0) return false; } int remainingBits = challengeSize - 8*bytes; if (remainingBits > 0) return a[bytes + 1]>>(8-remainingBits) == 0; else return true; } return false; } I've also tried the following which is approximately the same run time:
bool checkLeadingZeroBits(SHA256Hash& hash, unsigned int challengeSize) { int bytes = challengeSize / 8; const uint8_t * a = hash.data(); if (bytes == 0) { return a[0]>>(8-challengeSize) == 0; } else { if (memcmp(NULL_SHA256_HASH.data(), a, bytes) != 0) return false; int remainingBits = challengeSize - 8*bytes; if (remainingBits > 0) return a[bytes + 1]>>(8-remainingBits) == 0; else return true; } return false; } I'd like to optimize this function to run as quickly as possible. Is there a simpler way to check the leading order bits than using the for loops shown in my implementation?
charas eight bits.