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

二进制转字符串代码异常:输出不符预期求排查(main函数不可修改)

二进制转字符串函数错误排查与修复

问题描述

尝试将二进制数组转换为字符串,编写的decode_bytes函数输出不符合预期:预期输出为"hello",实际输出为"cel<mB",且不允许修改main函数。原代码如下:

#include <stdio.h>
#include <stdbool.h>
#include<math.h>
#include<string.h>

void decode_bytes(const int rows, bool bytes[rows][8], char string[rows]){
    int iteration = 8;

    for(int j = 0; j < rows; j++){
        for (int i = 0; i < iteration; i++){
            if (bytes[j][i] == 1){
                string[j] += pow(2, iteration - (i + 1));
            }
        }
    }
}

int main(){
bool bytes2[7][8] = {
    {0,1,0,0,1,0,0,0},
    {0,1,1,0,0,1,0,1},
    {0,1,1,0,1,1,0,0},
    {0,1,1,0,1,1,0,0},
    {0,1,1,0,1,1,1,1},
    {0,0,1,0,0,0,0,1},
    {0,0,0,0,0,0,0,0}
};
char string[7];
decode_bytes(7, bytes2, string);
printf("%s\n", string);
}

问题分析

  • 未初始化string数组元素:char string[7]在声明时未初始化,每个元素都是内存中的随机垃圾值,直接使用+=会把二进制计算结果叠加到垃圾值上,导致字符完全错误。
  • 使用pow函数的精度问题:pow是浮点运算函数,计算整数幂时可能出现精度误差(比如pow(2,3)可能返回7.999999999,强制转换为整数时会变成7),导致二进制转十进制的结果出错。
  • 缺少字符串结束符\0:C语言中字符串需要以\0结尾,printf("%s")会一直读取内存直到遇到\0,原代码未添加结束符,导致输出乱码。

修复后的代码

#include <stdio.h>
#include <stdbool.h>
#include<string.h>

void decode_bytes(const int rows, bool bytes[rows][8], char string[rows]){
    for(int j = 0; j < rows; j++){
        // 初始化当前字符为0,避免垃圾值干扰
        string[j] = 0;
        for (int i = 0; i < 8; i++){
            if (bytes[j][i] == 1){
                // 用位运算代替pow,避免浮点精度问题
                string[j] |= (1 << (7 - i));
            }
        }
    }
    // 在字符串末尾添加结束符,确保printf正常输出
    string[rows - 1] = '\0';
}

int main(){
bool bytes2[7][8] = {
    {0,1,0,0,1,0,0,0},
    {0,1,1,0,0,1,0,1},
    {0,1,1,0,1,1,0,0},
    {0,1,1,0,1,1,0,0},
    {0,1,1,0,1,1,1,1},
    {0,0,1,0,0,0,0,1},
    {0,0,0,0,0,0,0,0}
};
char string[7];
decode_bytes(7, bytes2, string);
printf("%s\n", string);
}

修复说明

  • 初始化字符值:每次处理行前先将string[j]设为0,确保从干净的初始值开始计算。
  • 位运算替代pow:用1 << (7 - i)计算2的幂,位运算属于整数操作,完全避免浮点精度问题。
  • 添加结束符:将数组最后一个元素设为\0,保证printf能正确识别字符串结束位置。

内容的提问来源于stack exchange,提问作者Grey D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:20:38