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

C++读取小端序二进制文件中整数的问题求助

问题解决:二进制小端序整数解析错误

问题原因

你把二进制格式的4字节整数直接存为string类型并输出,这些字节(0x13 0x00 0x00 0x00)并非可打印字符,所以输出乱码。需要将字节序列按小端序规则解析为整数。

修复步骤

  • 修改成员变量类型:将string age改为int age,匹配年龄的整数属性。
  • 解析小端序字节:从缓冲区提取4个字节,按小端序(低字节在前)组合成十进制整数。
  • 调整输出逻辑:直接输出整数类型的年龄即可。

修改后的完整代码

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class BinaryData
{
private:
   int      age;  // 改为int类型存储年龄
   string   firstName;
   string   lastName;  
public:
   BinaryData(){};
   ~BinaryData(){};
   void readStudentData(string fileName)
   {
      // 打开文件并获取大小
      ifstream in(fileName.c_str(), ios::in | ios::binary);
      in.seekg(0, ios::end);
      int fileSize = in.tellg();
      in.seekg(0, ios::beg);

      // 将整个文件读入缓冲区
      string studentBuffer;
      studentBuffer.resize(fileSize);
      in.read(&studentBuffer[0], studentBuffer.size());
      
      // 定位到学生信息起始位置
      int index = studentBuffer.find("StudentInfo");
      if(index != 0 && index != std::string::npos)
      {
          // 注意:若"StudentInfo"本身占字节,需先跳过该字符串(例:index += "StudentInfo".size();)
          // 按原代码逻辑,从index位置开始解析年龄

          // 小端序4字节整数解析
          age = static_cast<unsigned char>(studentBuffer[index]) |
                (static_cast<unsigned char>(studentBuffer[index+1]) << 8) |
                (static_cast<unsigned char>(studentBuffer[index+2]) << 16) |
                (static_cast<unsigned char>(studentBuffer[index+3]) << 24);
          index += 4;
          
          firstName = studentBuffer.substr(index, 10);
          index += 10;
          lastName = studentBuffer.substr(index, 10);
          
          std::cout<< "The student name is: " << firstName << " " << lastName << ", they are " << age << " years old" << std::endl;
      }
      in.close();
   }
};

关键说明

  • 用static_cast<unsigned char>转换字节,避免符号扩展导致的错误(比如0x80以上的有符号char会被识别为负数)。
  • 小端序组合逻辑:第一个字节对应整数的最低位(20),第二个对应28位,第三个216位,第四个224位,通过按位或组合成完整整数。
  • 若文件中"StudentInfo"字符串后才是年龄数据,需先将index移动到该字符串末尾,否则会从字符串字符位置开始读年龄,导致解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:12:18