请问如何读取二进制文件

rabbit729 2007-09-25 09:40:36
有如下二进制文件内容:
31 01 19 46 58

请问如何将每个字节读出并将其转化为unsigned short类型数据,比如将十六进制的31读出并转换为49?谢谢!!!!
...全文
190 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞羽飞之猪 2007-09-26
  • 打赏
  • 举报
回复
我把Chiyer的代码改了下,用下面的你试试

#include "iostream"
#include "fstream"
#include "string"
#include "iomanip"

using namespace std;

int main(int argc, char* argv[])
{
ifstream file("data.txt");

if (file.fail())
return 1;

while (!file.eof())
{
unsigned char tmp;
file>>tmp;
cout << (unsigned short)tmp << endl;
}


file.close();

return 0;
}
rabbit729 2007-09-26
  • 打赏
  • 举报
回复
to:Chiyer(星羽) ( )
------------------------
谢谢您的回复!
你的方法读文本的没问题!可能我没说清楚这个文件的内容,我的文件用txt打开后是乱码,用UltraEdit打开后用十六进制方式显示如下:31 01 19 46 58
不知如何解决这个问题
星羽 2007-09-25
  • 打赏
  • 举报
回复

#include "iostream"
#include "fstream"
#include "string"
#include "iomanip"

using namespace std;

int main(int argc, char* argv[])
{
ifstream file("data.txt");

if (file.fail())
return 1;

while (!file.eof())
{
string str;
file>>str;
int n;
sscanf(str.c_str(), "%x", &n);
cout<<n<<" ";
}


file.close();

return 0;
}

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧