FieryRMS
FieryRMS

Reputation: 111

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. I also tried read() but it didn't seem to work. 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?

Upvotes: 0

Views: 537

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36613

10110100 is 180.

On most platforms char is a signed 8-bit number with the range -128 to 127.

When you read in 10110100 a is set to -76.

76 is 01001100 in binary which matches your output.

Changing char to unsigned char should fix your problem:

unsigned char a;
while(input.read(reinterpret_cast<char*>(&a), 1))

Upvotes: 1

Related Questions