读书人

请教怎么读取二进制文件

发布时间: 2012-03-30 17:32:09 作者: rapoo

请问如何读取二进制文件
有如下二进制文件内容:
31 01 19 46 58

请问如何将每个字节读出并将其转化为unsigned short类型数据,比如将十六进制的31读出并转换为49?谢谢!!!!


[解决办法]

#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;
}

[解决办法]
我把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;
}

读书人网 >C++

热点推荐