I want to convert the text string from a file into binary and then create a new file holding these binary. I am using the VC++ 2008.

I have done some search on the internet, but hardly understand.
Can anyone give me idea or sample code with explanation?

Thanks in advance!

Dani AI

Generated

There are two different tasks that people mean by "convert text to binary." One is to produce a human-readable file of ASCII 0/1 characters (for example, "A" -> "01000001"). The other is to produce a binary file that contains the original bytes (compact, not expanded to text). is correct that a character is just an integer; below are practical, VC++2008-friendly examples for both approaches and a few cautions. 's serialization pointer is useful when you need to persist complex objects — for plain text-to-bits you don’t need a full serializer.

Convert to a text file of 0/1 per byte (one 8-bit group per input character):

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream in("input.txt", std::ios::in | std::ios::binary);
    std::ofstream out("out_bits.txt");
    if (!in || !out) return 1;

    char c;
    while (in.get(c)) {
        unsigned char uc = static_cast<unsigned char>(c); // avoid sign-extension
        for (int i = 7; i >= 0; --i)
            out.put(((uc >> i) & 1) ? '1' : '0');
        // optional separator: out.put(' ');
    }
    return 0;
}

Notes: cast to unsigned char to get consistent bit patterns; the loop writes MSB first and preserves leading zeros (so A becomes 01000001). This output is about 8x larger than the original. To reverse it, read groups of 8 characters and reconstruct the byte with bit shifts.

If the goal is simply a binary file that contains the same bytes (compact, not textual), copy in binary mode:

#include <fstream>

int main()
{
    std::ifstream in("input.txt", std::ios::binary);
    std::ofstream out("out.bin", std::ios::binary);
    out << in.rdbuf();
}

Cautions: open files with ios::binary to avoid CR/LF translation on Windows; handle UTF BOMs if input is Unicode; check file-open errors; decide on separators/newlines if you need human readability or reversible parsing.

Recommended Answers

All 4 Replies

what do you mean you want to convert it to binary? Like the letter A (which has a decimal value of 65) = 1000001?

yes, convert it to binary.

Thanks for link!

Do you know how to convert an integer to binary (characters are really integers). If you don't, then google and you will find out how. Once you have a function that does that then you should be able to convert all the characters in a file to binary.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.