Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <limits.h>
- #define BUFFER_SIZE (4096 * sizeof(char))
- #define INT32_BIT (CHAR_BIT * sizeof(int32_t))
- #define IS_POW2(x) ((x & (x - 1)) == 0)
- uint32_t hamming_encode(const char *src, char *dst, size_t dst_size)
- {
- uint32_t result = 0; // 0 - success
- char *ctrl[INT32_BIT], curc, *dst_end = dst + dst_size;
- uint32_t i = 1, q = 0, k = 0;
- while(dst < dst_end)
- {
- if (!IS_POW2(i))
- {
- if ((curc = *src) == '\0') break;
- ++src;
- if (curc == '1' || curc == '0')
- {
- if (curc == '1') q ^= i;
- *dst = curc;
- }
- else continue; // ignore invalid symbols
- }
- else ctrl[k++] = dst;
- ++i;
- ++dst;
- }
- for (i = 0; i < k; ++i)
- {
- *ctrl[i] = (q & 1) + '0';
- q >>= 1;
- }
- *dst = '\0';
- if (*src != '\0') result = 1; // 1 - output buffer is small
- return result;
- }
- uint32_t hamming_check(const char *str)
- {
- uint32_t i = 1, q = 0;
- for (; *str != '\0'; ++str, ++i)
- {
- if (*str == '1') q ^= i;
- }
- return q; // 0 - success, no errors
- }
- void hamming_decode(char *str)
- {
- uint32_t i = 1;
- char *dst = str;
- for (; *str != '\0'; ++str, ++i)
- {
- if (!IS_POW2(i)) *dst++ = *str;
- }
- *dst = '\0';
- }
- int main()
- {
- // const char *src = "1110000100";
- char src[BUFFER_SIZE];
- char dst[BUFFER_SIZE];
- uint32_t error_code;
- printf("Enter bit-string to hamming encode/decode:\n");
- fgets(src, BUFFER_SIZE, stdin);
- if ((error_code = hamming_encode(src, dst, BUFFER_SIZE)) == 0)
- {
- printf("%s\n", dst);
- if ((error_code = hamming_check(dst)) == 0)
- {
- printf("Hamming code is valid. Decode...\n");
- hamming_decode(dst);
- printf("%s\n", dst);
- }
- else printf("Hamming code is INVALID. Error code: %d!\n", error_code);
- }
- else fprintf(stderr, "Error: output buffer is small.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement