Advertisement
pasholnahuy

Untitled

Dec 18th, 2023
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #include <stddef.h>
  2. #include <stdint.h>
  3.  
  4. uint16_t hamming812(uint8_t byte) {
  5. return (__builtin_parity(byte & 0b11011010) << 15) | // 16
  6. (__builtin_parity(byte & 0b10110110) << 14) | // 15
  7. ((byte & 0b10000000) << 6) | // 14
  8. (__builtin_parity(byte & 0b01110001) << 12) | // 13
  9. ((byte & 0b01110000) << 5) | // 12 - 10
  10. (__builtin_parity(byte & 0b00001111) << 8) | // 9
  11. (byte & 0b00001111) << 4; // 8-5
  12. }
  13.  
  14. void encode(void *data, void *encoded, size_t n) {
  15. for (size_t i = 0; i < n; ++i) {
  16. uint8_t byte = ((uint8_t *)data)[i];
  17. ((uint16_t *)encoded)[i] = hamming812(byte);
  18. }
  19. }
  20.  
  21. uint8_t hamming_decode(uint16_t enc) {
  22. int err1 = __builtin_parity(enc & 0b1010101010100000);
  23. int err2 = __builtin_parity(enc & 0b0110011001100000);
  24. int err4 = __builtin_parity(enc & 0b0001111000010000);
  25. int err8 = __builtin_parity(enc & 0b0000000111110000);
  26. if (!(err1 | err2 | err4 | err8)) {
  27. return ((enc & 0b0010000000000000) >> 6) |
  28. ((enc & 0b0000111000000000) >> 5) |
  29. ((enc & 0b0000000011110000) >> 4);
  30. }
  31. int ind = err1 + (err2 << 1) + (err4 << 2) + (err8 << 3);
  32. uint16_t fixed_enc = enc ^ (1 << (16 - ind));
  33. return ((fixed_enc & 0b0010000000000000) >> 6) |
  34. ((fixed_enc & 0b0000111000000000) >> 5) |
  35. ((fixed_enc & 0b0000000011110000) >> 4);
  36. }
  37.  
  38. void decode(void *encoded, void *data, size_t n) {
  39. for (size_t i = 0; i < n; ++i) {
  40. ((uint8_t *)data)[i] = hamming_decode(((uint16_t *)encoded)[i]);
  41. }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement