diff --git a/13.md b/13.md index 0900d2d7..cf5b1acd 100644 --- a/13.md +++ b/13.md @@ -48,37 +48,30 @@ Validating Here is some reference C code for calculating the difficulty (aka number of leading zero bits) in a nostr event id: ```c -#include -#include -#include +int zero_bits(unsigned char b) +{ + int n = 0; -int countLeadingZeroes(const char *hex) { - int count = 0; + if (b == 0) + return 8; - for (int i = 0; i < strlen(hex); i++) { - int nibble = (int)strtol((char[]){hex[i], '\0'}, NULL, 16); - if (nibble == 0) { - count += 4; - } else { - count += __builtin_clz(nibble) - 28; - break; - } - } + while (b >>= 1) + n++; - return count; + return 7-n; } -int main(int argc, char *argv[]) { - if (argc != 2) { - fprintf(stderr, "Usage: %s \n", argv[0]); - return 1; - } - - const char *hex_string = argv[1]; - int result = countLeadingZeroes(hex_string); - printf("Leading zeroes in hex string %s: %d\n", hex_string, result); - - return 0; +/* find the number of leading zero bits in a hash */ +int count_leading_zero_bits(unsigned char *hash) +{ + int bits, total, i; + for (i = 0, total = 0; i < 32; i++) { + bits = zero_bits(hash[i]); + total += bits; + if (bits != 8) + break; + } + return total; } ```