binary format

hi everyone
i want to open a text file in its original binary format i.e. to open it as its' content are stored in the memory in form of 0s and 1s. for examle a file storing charecter 'a' should be read and displayed as 01100011 and i also require to write to a text file in same manner. can anyone tell me how this is possible?? i tried opening it in ios::binary but didnt get the required results..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
#include <bitset>
#include <limits>

int main()
{
    // open the file
    std::ifstream file( __FILE__, std::ios::binary ) ;
    file >> std::noskipws ; // do not skip whitespace characters
    
    unsigned char byte ;
    int n = 0 ;
    
    while( file >> byte ) // for each byte in the file
    {
        // print out the bits in the byte
        std::cout << std::bitset< std::numeric_limits<unsigned char>::digits >(byte) << ' ' ; 
        if( ( n++ % 16 ) == 15 ) std::cout << '\n' ; // 16 bytes per line
    }
}

http://coliru.stacked-crooked.com/a/c2bb7f6c583329b6

Use the same technique for writing:
string of zeroes and ones in the byte => bitset => unsigned long => unsigned char => file.
Last edited on
thanks a lot but i didnt understand the code
std::bitset< std::numeric_limits<unsigned char>::digits >(byte)
properly furthermore i want to store the bits into a variable for some manipulations
I think OP is confused about what "binary format" means.

The only difference between "binary format" and "textual format" is that the first is not necessarily designed to be read by humans.

For example, suppose I had an integer value:

 
int x = -7;

If I wanted to store that value in a file, I could transform it into a human-readable form, storing the two characters "-7":

1
2
3
ofstream outf( "foo.txt" );
outf << x;
outf.close();

I could, however, decide to store it directly, without transforming it into something humans can read.

1
2
3
ofstream outf( "foo.dat", ios::binary );
outf.write( (const char*)&x, sizeof int );
outf.close();

This code has endianness issues, but it suffices to demonstrate the issue.

You can now read the two appropriately:

1
2
3
4
5
ifstream inf( "foo.txt" );
int y;
inf >> y;
inf.close();
if (x == y) cout << "Yeah!\n";
1
2
3
4
5
ifstream inf( "foo.dat", ios::binary );
int y;
inf.read( (char *)&y, sizeof int );
inf.close();
if (x == y) cout << "Yeah!\n";


So, by "binary", what we really mean is that there is no textual transformation required. It's the difference between a .docx file and a .txt file. The difference between an .exe and a .cpp.

The 0's and 1's themselves are actually a human way of looking at the information. JLBorges is providing you information on how to convert your data to/from the human-readable 0's and 1's 'binary' format.

Hope this helps.
Topic archived. No new replies allowed.