You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

M1 MacBook Air上GCC编译汉明码程序输出垃圾值求助

修复汉明码程序本地执行的垃圾值问题

问题根源

你的代码核心错误是未为校验位预留数组空间,且访问了未初始化的内存区域:

  • 汉明码需要将校验位放在2的幂次位置,数据位填充到剩余位置,但原代码直接把输入的n个数据存在数组开头,没有预留校验位的位置。
  • 打印时直接访问n+m长度的数组,但原数组仅前n位有有效数据,后m位是未初始化的随机值,导致输出垃圾字符。

修复方案

关键修改点

  1. 单独创建汉明码数组并初始化:避免未初始化内存的干扰,数组长度设为n+m(数据位+校验位总数)。
  2. 正确填充数据位:将输入数据放到汉明码数组的非校验位位置,校验位位置初始化为0。
  3. 修正校验位计算逻辑:基于完整的汉明码数组计算校验位,确保遍历范围正确。

修改后的完整代码

#include <stdio.h>

// 判断0-based索引是否为校验位位置(对应1-based的2^i位置)
int isParityPosition(int pos) {
    return (pos & (pos + 1)) == 0;
}

// 计算奇校验位并填充到汉明码数组
void calculateParityBits(int hamming[], int totalLength, int m) {
    int i, j, k;
    for (i = 0; i < m; i++) {
        int parityPosNum = 1 << i; // 1-based的校验位位置
        int parityIndex = parityPosNum - 1; // 转成0-based索引
        int count = 0;

        // 遍历当前校验位覆盖的所有位置
        for (j = parityPosNum; j <= totalLength; j += 2 * parityPosNum) {
            for (k = 0; k < parityPosNum && (j + k) <= totalLength; k++) {
                int currentIndex = (j + k) - 1;
                if (hamming[currentIndex] == 1) {
                    count++;
                }
            }
        }

        // 奇校验:1的数量为奇数时,校验位设为1
        hamming[parityIndex] = (count % 2 != 0) ? 1 : 0;
    }
}

// 打印汉明码
void printHammingCode(int hamming[], int totalLength) {
    int i;
    for (i = 0; i < totalLength; i++) {
        printf("%d", hamming[i]);
    }
    printf("\n");
}

int main() {
    int data[100];
    int hamming[100] = {0}; // 初始化汉明码数组为0,避免垃圾值
    int n, m;

    printf("Enter the length of the data: ");
    scanf("%d", &n);
    printf("Enter the number of parity bits: ");
    scanf("%d", &m);
    int totalLength = n + m;

    printf("Enter the data bits: ");
    int dataIdx = 0;
    // 将数据位填充到非校验位位置
    for (int i = 0; i < totalLength && dataIdx < n; i++) {
        if (!isParityPosition(i)) {
            scanf("%d", &hamming[i]);
            dataIdx++;
        }
    }

    // 计算校验位
    calculateParityBits(hamming, totalLength, m);

    // 打印结果
    printf("Hamming code: ");
    printHammingCode(hamming, totalLength);

    return 0;
}

测试验证

使用你提供的输入:

Enter the length of the data: 4  
Enter the number of parity bits: 3
Enter the data bits: 1
0
1
0

正确输出应为:

Hamming code: 1011010

内容的提问来源于stack exchange,提问作者Kartikey Doshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:12:04