Reputation: 1
I'm trying to figure out a way to manipulate the binary code of any file in the computer in goal to apply a compress/decompress algorithm in c++ . I have been searching about that for long time and all i found was how to read a .bin file :
#include <iostream>
#include <fstream>
using namespace std;
int main (){
streampos size;
char * memblock;
ifstream file ("name.bin", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char[size];
file.seekg (0, ios::beg);
file.read (memblock, size);
for(int i = 0 ; i < size ; i++){
cout << memblock[i] ;
}
file.close();
cout << "\n\n the entire file content is in memory";
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
I just wanna those bytes without ASCII translation, other words i wanna all the file as binary not what is inside it
Upvotes: 0
Views: 62
Reputation: 1
The answer was simpler than we thought :
for(int i = 0 ; i < size ; i++){
//changing the value of "memblock[i]" to binary byte per byte with for loop
//and of course using bitset
bitset<8> test (memblock[i]);
cout << test ;
}
Upvotes: 0
Reputation: 4288
<<
is overloaded for char
types to output the ASCII formated character. The data (the ones and zeros) in your memblock
array are accurately read in as binary. It's just the way you're displaying them that is ASCII. Instead of a char[]
for memblock
, make it a uint8_t[]
. Then, when you output, do
std::cout << std::hex << std::fill('0') << std::setw(2) << memblock[i];
^ ^ ^
| | |
| | sets the width of the next output
| sets the fill character (default is space)
tells the stream to output all numbers in hexadecimal
You'll have to #include <iomanip>
for the stream format manipulators hex
, fill
, and setw
to work.
Note that setw
will only be set on the stream for the next output operation, while hex
and fill
will be set until explicitly set otherwise. That said, you only need to set these two manipulators once, probably outside your loop. Then when you're finished, you can set them back like:
std::cout << std::dec << std::fill(' ');
See https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2 for the list of overloaded operator<<
functions for char
and char
arrays.
Upvotes: 2