[英]File not read correctly in binary mode C++
I have a binary file with the following data,我有一个包含以下数据的二进制文件,
10110100
11111001
01110001
and I used this code to read it,我用这段代码来阅读它,
#include<bits/stdc++.h>
using namespace std;
int main()
{
string in;
cin>>in;
ifstream input(in.c_str(),ios::in | ios::binary);
if(!input.is_open())
{
cout<<"oops!!"<<endl;
return 0;
}
cout<<"OK!!"<<endl;
char a;
while(input.get(a))
{
string s="";
int b=a,c=0;
while(b!=0)
{
c++;
s+=(b%2?'1':'0');
b/=2;
}
s+=string(8-c,'0');
for(int i=s.length()-1;i>=0;i--)
cout<<s[i];
cout<<endl;
}
cout<<endl<<"DONE!!"<<endl;
}
Which basically reads a character, 1 byte, from the file using get()
function and outputs it as a binary representation.它基本上使用
get()
函数从文件中读取一个字符,1 个字节,并将其输出为二进制表示。 I also tried read()
but it didn't seem to work.我也试过
read()
但它似乎没有用。 I get the following output if it helps,如果有帮助,我会得到以下输出,
01001100
00000111
01110001
There is no other data in the file, I checked with a binary editor.文件中没有其他数据,我用二进制编辑器检查过。 What problem am I having?
我有什么问题?
10110100
is 180. 10110100
是 180。
On most platforms char
is a signed 8-bit number with the range -128
to 127
.在大多数平台上,
char
是一个有符号的 8 位数字,范围为-128
到127
。
When you read in 10110100
a
is set to -76
.当您读入
10110100
a
设置为-76
。
76
is 01001100
in binary which matches your output. 76
是二进制的01001100
,与您的输出相匹配。
Changing char
to unsigned char
should fix your problem:将
char
更改为unsigned char
应该可以解决您的问题:
unsigned char a;
while(input.read(reinterpret_cast<char*>(&a), 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.