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 & 0b0000000111110000);
- 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]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement