I'm trying to convert an mp3 into a binary fstream (or hexadecimal, I can use both). I've figured out how to open the file and output the contents to the console. But in both binary and hex, the leading 0's are removed. Therefore, if I create a new mp3 from the fstream it will be missing many bits. Any help in preserving the original formatting would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile; // Declare variable to hold the location of file
myfile.open("src/ShortTest.mp3", std::ios::binary); //open short file with sample data
if (!myfile.is_open())
{
cout << "Cannot read file!" << endl;
}
else
{
cout << "File is open!" << endl;
while ( getline (myfile,line) ) {
int n = line.length();
int remainder = 0;
for (int i = 0; i <= n; i++) {
// convert each char to
// ASCII value
int val = int(line[i]);
// Convert ASCII value to binary
string bin = "";
while (val > 0) {
(val % 2)? bin = '1'+bin : bin = '0'+bin ;
val /= 2;
}
cout << bin << " ";
remainder = (i+1) % 8;
if ( remainder == 0) {
cout << endl;
}
}
}
myfile.close();
}
cout << "Done!" << endl;
return 0;
}
Output:
File is open!
1001001 1000100 110011 11 1
1001 1100010 1010100 1001001 1010100 110010
1100 1010011 1110100 1110101
1110000 1101001 1100100 100000 1010011 1101111 1101110 1100111
1010100 1000011 1001111 1001110 111
1001111 1110100 1101000 1100101 1110010
1010100 1001011 1000101 1011001
10 1000101 1010100 1011000 1011000
Done!
My expected output is what I see in a hex editor
File is open!
01001001 01000100 00110011 00000011 00000000 00000000 00000000 00000001
00001001 01100010 01010100 01001001 01010100 00110010 00000000 00000000
00000000 00001100 00000000 00000000 00000000 01010011 01110100 01110101
01110000 01101001 01100100 00100000 01010011 01101111 01101110 01100111
01010100 01000011 01001111 01001110 00000000 00000000 00000000 00000111
00000000 00000000 00000000 01001111 01110100 01101000 01100101 01110010
00000000 01010100 01001011 01000101 01011001 00000000 00000000 00000000
00000010 00000000 00000000 00000000 01000101 01010100 01011000 01011000
Done!