c++ - 读取十六进制文件 C++
问题描述
我正在尝试使用十六进制格式从文件中一次读取两个字符。问题是每当十六进制字符中包含 0 时,它在打印时都会被忽略。前任。08 只是显示为 8。我怎样才能确保它不会省略 0?它是否涉及某种位移?
std::ifstream stream;
stream.open(file_path, std::ios_base::binary);
if (!stream.bad()) {
std::cout << std::hex;
std::cout.width(2);
while (!stream.eof()) {
unsigned char c;
stream >> c;
cout << (short)c <<'\n';
}
}
解决方案
如果您只想显示 2 位数字,则可以在输出中启用 1 前导零:
#include <iomanip>
...
cout << std::hex << setfill('0'); //Set the leading character as a 0
cout << std::setw(2) //If output is less than 2 charaters then it will fill with setfill character
<< 8; //Displays 08
//In your example
unsigned char c;
stream >> c;
cout << std::setw(2) << (short)c <<'\n';
推荐阅读
- devise - 防止在 rails/devise 中没有邀请码的情况下登录
- python - 从现有的词典列表中制作新的词典列表?
- select - 在 SQL Server 中选择记录
- dart - 在加载 url 之前,如何使用缓存图像在颤动中显示?
- r - 年龄作为生存分析中的时间尺度
- google-api - 为什么我会得到非常不一致的 Google Geocode API 结果?
- csvhelper - 在 CsvHelper v7.1.1 中读取“未键入”的 CSV 文件
- c# - 如何根据单击的按钮在 div 中显示数据:C# MVC
- excel - 添加 7 个单元格中最好的 5 个的总和
- jquery - jQuery if 语句使用需要选择部分中的所有页面的 URL,但有例外