Advertisement
pasholnahuy

Untitled

Dec 18th, 2023
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 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 & 0b0000000011110000);
  26. if (!(err1 | err2 | err4 | err8)) {
  27. return ((enc & 0b0010000000000000) >> 6) | ((enc & 0b0000111000000000) >> 5) | ((enc & 0b0000000011110000) >> 4);
  28. }
  29. int ind = err1 + (err2 << 1) + (err4 << 2) + (err8 << 3);
  30. uint16_t fixed_enc = enc ^ (1 << (16 - ind));
  31. return ((fixed_enc & 0b0010000000000000) >> 6) | ((fixed_enc & 0b0000111000000000) >> 5) | ((fixed_enc & 0b0000000011110000) >> 4);
  32. }
  33.  
  34. void decode(void *encoded, void *data, size_t n) {
  35. for (size_t i = 0; i < n; ++i) {
  36. ((uint8_t *)data)[i] =
  37. hamming_decode(((uint16_t *)encoded)[i]);
  38. }
  39. }
  40. #include <assert.h>
  41. #include <stdbool.h>
  42. #include <stddef.h>
  43. #include <stdint.h>
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46. #include <string.h>
  47.  
  48.  
  49. void generate_random_data(void *buffer, size_t n) {
  50. for (size_t i = 0; i < n; ++i) {
  51. ((uint8_t *)buffer)[i] = rand();
  52. }
  53. }
  54.  
  55. void bitflip(void *buffer, size_t n) {
  56. if (rand() % n) {
  57. ((uint8_t *)buffer)[rand() % n] ^= (1 << (rand() % 8));
  58. }
  59. }
  60.  
  61. void test() {
  62. const size_t n = 1;
  63. void *data = malloc(n);
  64. generate_random_data(data, n);
  65.  
  66. void *encoded_buffer = malloc(2 * n);
  67. encode(data, encoded_buffer, n);
  68. bitflip(encoded_buffer, n);
  69.  
  70. void *decoded_buffer = malloc(n);
  71. decode(encoded_buffer, decoded_buffer, n);
  72. assert(memcmp(data, decoded_buffer, n) == 0);
  73. free(encoded_buffer);
  74. free(data);
  75. free(decoded_buffer);
  76. }
  77.  
  78. int main() {
  79. size_t counter = 0;
  80. for (int _ = 0; _ < 10000; ++_) {
  81. test();
  82. printf("%zu tests passed...\n", ++counter);
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement