hamming distance
This commit is contained in:
parent
e622107f07
commit
c81c8bfa3c
@ -89,3 +89,11 @@ responsible for freeing the returned array
|
|||||||
```c
|
```c
|
||||||
const unsigned char *repeating_key_xor_s(const char* s, const char* key);
|
const unsigned char *repeating_key_xor_s(const char* s, const char* key);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### hamming_distance
|
||||||
|
|
||||||
|
Calculates the Hamming Distance (the number of differing bits) between two strings
|
||||||
|
|
||||||
|
```c
|
||||||
|
unsigned int hamming_distance(const char *a, const char *b);
|
||||||
|
```
|
||||||
|
@ -13,4 +13,6 @@ const char *hex_to_str(const unsigned char *hex, size_t sz);
|
|||||||
const unsigned char* repeating_key_xor(const unsigned char* s, size_t s_sz, const unsigned char* key, size_t k_sz);
|
const unsigned char* repeating_key_xor(const unsigned char* s, size_t s_sz, const unsigned char* key, size_t k_sz);
|
||||||
const unsigned char *repeating_key_xor_s(const char* s, const char* key);
|
const unsigned char *repeating_key_xor_s(const char* s, const char* key);
|
||||||
|
|
||||||
|
unsigned int hamming_distance(const char *a, const char *b);
|
||||||
|
|
||||||
#endif // LIBFLINT_CRYPTO_H
|
#endif // LIBFLINT_CRYPTO_H
|
||||||
|
22
src/crypto.c
22
src/crypto.c
@ -271,3 +271,25 @@ const unsigned char* repeating_key_xor(const unsigned char* s, size_t s_sz, cons
|
|||||||
const unsigned char *repeating_key_xor_s(const char* s, const char* key) {
|
const unsigned char *repeating_key_xor_s(const char* s, const char* key) {
|
||||||
return repeating_key_xor((unsigned char*)s, strlen(s), (unsigned char*)key, strlen(key));
|
return repeating_key_xor((unsigned char*)s, strlen(s), (unsigned char*)key, strlen(key));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unsigned int hamming_distance(const char *a, const char *b) {
|
||||||
|
size_t sz = strlen(a);
|
||||||
|
if (sz != strlen(b)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int hamming = 0;
|
||||||
|
for (size_t i = 0; i < sz; ++i) {
|
||||||
|
if (a[i] == b[i]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
unsigned char c = a[i] ^ b[i];
|
||||||
|
unsigned int count = 0;
|
||||||
|
for (; c; count++) {
|
||||||
|
c &= c - 1;
|
||||||
|
}
|
||||||
|
hamming += count;
|
||||||
|
}
|
||||||
|
|
||||||
|
return hamming;
|
||||||
|
}
|
||||||
|
@ -374,6 +374,9 @@ void test_crypto() {
|
|||||||
free(enc);
|
free(enc);
|
||||||
free(s);
|
free(s);
|
||||||
|
|
||||||
|
unsigned int hamming = hamming_distance("this is a test", "wokka wokka!!!");
|
||||||
|
assert(hamming == 37);
|
||||||
|
|
||||||
printf("Passes all crypto tests\n");
|
printf("Passes all crypto tests\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user