MMMMMCK
MMMMMCK

Reputation: 337

Unexpected Result When Writing Binary Number To File [C++]

I'm writing what should be quite a simple function in Linux that takes an integer, converts it to a 4 byte binary string, and writes it to a binary file.


The function:

void writeToBinaryFile(int number){
    remove("path/fileToWriteTo.img");  //remove outdated version of file

    ofstream output("path/fileToWriteTo.img", ios::binary);

    string binaryString = bitset<32>(number).to_string();
    cout << "BINARY DATA IS " << binaryString << endl; 
    //This looks perfect, an example entry of 81 results in an output of
    //BINARY DATA IS 00000000000000000000000001010001

    output.seekp(0);
    output.write(binaryString.c_str(), 4);  //write these 4 bytes into binary file
    output.close();
}

This function compiles and runs without an issue, however, when I hexdump the contents of fileToWriteTo.img, the result is wrong. The correct hexdump after running writeToBinaryFile(81) should be 0000 0051, as an example.

However, the ACTUAL hexdump is 3030 3030, and it remains this no matter what integer I pass to writeToBinaryFile(). I feel like there's something fairly trivial I'm missing with this attempt to write the string to a file in binary format, but currently am at a loss for what's happening.

Upvotes: 0

Views: 196

Answers (1)

R Sahu
R Sahu

Reputation: 206747

You realized that binaryString is "00000000000000000000000001010001".

When you use

output.write(binaryString.c_str(), 4);

you are writing the first 4 characters of the string, which are all '0's. What probably got you confused was that you were expecting to see the number zero but what you asked the program to write is the character '0'. The ASCII encoding value for '0' is 48 in decimal, which is 0x30. That's what you are seeing in your file -- four 0x30s.

If you want to write the number to file in binary, you can use the following, without jumping through the bitset hoop.

void writeToBinaryFile(int number)
{
    ofstream output("path/fileToWriteTo.img", ios::binary);
    output.write(reinterpret_cast<char cons*>(&number), sizeof(number));
}

You don't need the other lines in the function at all.

Upvotes: 1

Related Questions