diff options
| author | Jon Staab <shtaab@gmail.com> | 2024-09-09 12:38:51 -0700 |
|---|---|---|
| committer | fiatjaf_ <fiatjaf@gmail.com> | 2024-09-09 17:41:57 -0300 |
| commit | e7eb776288b424e8cd43080b33b21506942f91e0 (patch) | |
| tree | 116023a30217b6ea8634b795ef2b3580f83726c0 /13.md | |
| parent | 7edd3d23a953494bcce5def703a0d7a02a5ffa9c (diff) | |
Revert example code update
Diffstat (limited to '13.md')
| -rw-r--r-- | 13.md | 47 |
1 files changed, 20 insertions, 27 deletions
| @@ -48,37 +48,30 @@ Validating | |||
| 48 | Here is some reference C code for calculating the difficulty (aka number of leading zero bits) in a nostr event id: | 48 | Here is some reference C code for calculating the difficulty (aka number of leading zero bits) in a nostr event id: |
| 49 | 49 | ||
| 50 | ```c | 50 | ```c |
| 51 | #include <stdio.h> | 51 | int zero_bits(unsigned char b) |
| 52 | #include <stdlib.h> | 52 | { |
| 53 | #include <string.h> | 53 | int n = 0; |
| 54 | |||
| 55 | int countLeadingZeroes(const char *hex) { | ||
| 56 | int count = 0; | ||
| 57 | |||
| 58 | for (int i = 0; i < strlen(hex); i++) { | ||
| 59 | int nibble = (int)strtol((char[]){hex[i], '\0'}, NULL, 16); | ||
| 60 | if (nibble == 0) { | ||
| 61 | count += 4; | ||
| 62 | } else { | ||
| 63 | count += __builtin_clz(nibble) - 28; | ||
| 64 | break; | ||
| 65 | } | ||
| 66 | } | ||
| 67 | 54 | ||
| 68 | return count; | 55 | if (b == 0) |
| 69 | } | 56 | return 8; |
| 70 | 57 | ||
| 71 | int main(int argc, char *argv[]) { | 58 | while (b >>= 1) |
| 72 | if (argc != 2) { | 59 | n++; |
| 73 | fprintf(stderr, "Usage: %s <hex_string>\n", argv[0]); | ||
| 74 | return 1; | ||
| 75 | } | ||
| 76 | 60 | ||
| 77 | const char *hex_string = argv[1]; | 61 | return 7-n; |
| 78 | int result = countLeadingZeroes(hex_string); | 62 | } |
| 79 | printf("Leading zeroes in hex string %s: %d\n", hex_string, result); | ||
| 80 | 63 | ||
| 81 | return 0; | 64 | /* find the number of leading zero bits in a hash */ |
| 65 | int count_leading_zero_bits(unsigned char *hash) | ||
| 66 | { | ||
| 67 | int bits, total, i; | ||
| 68 | for (i = 0, total = 0; i < 32; i++) { | ||
| 69 | bits = zero_bits(hash[i]); | ||
| 70 | total += bits; | ||
| 71 | if (bits != 8) | ||
| 72 | break; | ||
| 73 | } | ||
| 74 | return total; | ||
| 82 | } | 75 | } |
| 83 | ``` | 76 | ``` |
| 84 | 77 | ||