Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stddef.h>
- #include <stdint.h>
- uint16_t hamming812(uint8_t byte) {
- return (__builtin_parity(byte & 0b11011010) << 15) | //16
- (__builtin_parity(byte & 0b10110110) << 14) | //15
- ((byte & 0b10000000) << 6) | //14
- (__builtin_parity(byte & 0b01110001) << 12) | //13
- ((byte & 0b01110000) << 5) | //12 - 10
- (__builtin_parity(byte & 0b00001111) << 8) | //9
- (byte & 0b00001111) << 4; //8-5
- }
- void encode(void *data, void *encoded, size_t n) {
- for (size_t i = 0; i < n; ++i) {
- uint8_t byte = ((uint8_t *)data)[i];
- ((uint16_t *)encoded)[i] = hamming812(byte);
- }
- }
- uint8_t hamming_decode(uint16_t enc) {
- int err1 = __builtin_parity(enc & 0b1010101010100000);
- int err2 = __builtin_parity(enc & 0b0110011001100000);
- int err4 = __builtin_parity(enc & 0b0001111000010000);
- int err8 = __builtin_parity(enc & 0b0000000011110000);
- if (!(err1 | err2 | err4 | err8)) {
- return ((enc & 0b0010000000000000) >> 6) | ((enc & 0b0000111000000000) >> 5) | ((enc & 0b0000000011110000) >> 4);
- }
- int ind = err1 + (err2 << 1) + (err4 << 2) + (err8 << 3);
- uint16_t fixed_enc = enc ^ (1 << (16 - ind));
- return ((fixed_enc & 0b0010000000000000) >> 6) | ((fixed_enc & 0b0000111000000000) >> 5) | ((fixed_enc & 0b0000000011110000) >> 4);
- }
- void decode(void *encoded, void *data, size_t n) {
- for (size_t i = 0; i < n; ++i) {
- ((uint8_t *)data)[i] =
- hamming_decode(((uint16_t *)encoded)[i]);
- }
- }
- #include <assert.h>
- #include <stdbool.h>
- #include <stddef.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void generate_random_data(void *buffer, size_t n) {
- for (size_t i = 0; i < n; ++i) {
- ((uint8_t *)buffer)[i] = rand();
- }
- }
- void bitflip(void *buffer, size_t n) {
- if (rand() % n) {
- ((uint8_t *)buffer)[rand() % n] ^= (1 << (rand() % 8));
- }
- }
- void test() {
- const size_t n = 1;
- void *data = malloc(n);
- generate_random_data(data, n);
- void *encoded_buffer = malloc(2 * n);
- encode(data, encoded_buffer, n);
- bitflip(encoded_buffer, n);
- void *decoded_buffer = malloc(n);
- decode(encoded_buffer, decoded_buffer, n);
- assert(memcmp(data, decoded_buffer, n) == 0);
- free(encoded_buffer);
- free(data);
- free(decoded_buffer);
- }
- int main() {
- size_t counter = 0;
- for (int _ = 0; _ < 10000; ++_) {
- test();
- printf("%zu tests passed...\n", ++counter);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement