用c语言实现海明码代码
时间: 2024-05-02 10:13:16 浏览: 130
以下是用C语言实现海明码的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int k, n, i, j, p, q, r, s, t, u, v, w, x, y, z;
int *data, *code, *temp;
printf("请输入信息码的位数k:");
scanf("%d", &k);
printf("请输入校验位的位数n:");
scanf("%d", &n);
data = (int *)malloc(sizeof(int) * k);
code = (int *)malloc(sizeof(int) * (k + n));
temp = (int *)malloc(sizeof(int) * (k + n));
printf("请输入%d位信息码:", k);
for (i = 0; i < k; i++)
{
scanf("%d", &data[i]);
}
p = 0;
q = 0;
while (p < k)
{
if (pow(2, q) - 1 == p + q)
{
q++;
}
else
{
code[p + q] = data[p];
p++;
}
}
for (i = 0; i < n; i++)
{
r = pow(2, i);
s = 0;
t = r;
while (t <= k + n)
{
for (j = t; j < t + r && j <= k + n; j++)
{
if (j != r && j != t - 1)
{
s = s ^ code[j - 1];
}
}
t = t + 2 * r;
}
code[r - 1] = s;
}
printf("海明码为:");
for (i = 0; i < k + n; i++)
{
printf("%d", code[i]);
}
printf("\n");
printf("请输入接收到的%d位码:", k + n);
for (i = 0; i < k + n; i++)
{
scanf("%d", &temp[i]);
}
u = 0;
for (i = 0; i < n; i++)
{
v = pow(2, i);
w = 0;
x = v;
while (x <= k + n)
{
for (j = x; j < x + v && j <= k + n; j++)
{
if (j != v && j != x - 1)
{
w = w ^ temp[j - 1];
}
}
x = x + 2 * v;
}
if (w != temp[v - 1])
{
u = u + v;
}
}
if (u == 0)
{
printf("接收到的码没有错误。\n");
}
else
{
printf("接收到的码第%d位出现了错误。\n", u);
if (temp[u - 1] == 0)
{
temp[u - 1] = 1;
}
else
{
temp[u - 1] = 0;
}
printf("正确的码为:");
for (i = 0; i < k + n; i++)
{
printf("%d", temp[i]);
}
printf("\n");
}
free(data);
free(code);
free(temp);
return 0;
}
```
阅读全文