• 01-30-2005
Varg Vikernes
I want to read a file and store it's bits into a txt file (from start to finish) so I can later reconstruct the exact binary from that txt file. Can anyone help me how to read bit's of a file and how to make a binary from them?
• 01-30-2005
sean
There are two ways to do file I/O - binary is on of them. Binary file I/O allows you to read raw data types in and out, and has several disadvantages to it's use, so despite the name, the easier method here is actually going to be using the more common method. Look at the file I/O tutorials on this site to get comfortable with how it's done - the wording of your question implies that you are not.

You can store the information from a file in a char variable - 1 byte (which we can assume to be 8 bits). You can determine whether or not a certain bit in that byte is 1 or 0 by doing what is called bit-masking. You using the binary logical operators and a "mask" variable, and check the outcome to see if a bit was set or not (there's a tutorial on it on this site I believe - if you're confused at this point, you need to go and read it).

- Read the original file into a C-style string
- Declare another C-style string, 8 times the size
- Using a system of two loops, cycle through each element of the original string
- Check each bit of each element
- Upon testing each bit, write the representation of the bit ('1', or '0') to the next element in your second string.

edit:
http://www.cprogramming.com/tutorial/lesson10.html (File I/O)
http://faq.cprogramming.com/cgi-bin/...&id=1073086407 (Working with binary)
• 01-30-2005
Shakti
If you want a shorter solution this is what I would do:
-read everything in to a vector of unsigned char's.
-have a loop, go through each element and use a bitset to output the bits to another file
-close and be happy.
• 01-31-2005
DougDbug
Are you trying to do encryption?

I'm not sure what you're trying to do, but a few points that might help you get on the right track:

When we're talking about file I/O, binary does not mean base-2. It just means "raw" or "as-is". There is very little difference between reading and writing text in ASCII or "binary". The difference is line-termination. If you save a C-style string in binary, the null-termination gets saved as-is (as a zero) to the file. If you save a C-style string as ASCII, the null-termination will get converted to an ASCII carrage-return and/or line-feed, depending on your system. In either case, the characters in the string will be saved as their ASCII values.

Since all characters are represented by a number, you don't have to convert them to binary to perform bit-manipulation. The characters are already stored as binary (base-2), although C++ sort-of hides that fact by "automatically" displaying numbers in decimal, and characters as characters. It can be helpful to display the values in hex or binary if you want to see what's happening.