0

I am trying to get some data to write to a binary file. The data consists of multiple values (strings, decimal, ints) that need to be a single string and then written to a binary file.

What I have so far creates the file, but it's putting my string in there as they appear and not converting them to binary, which I assume should look like 1010001010 etc. when I open the file in notepad?

The actual output is Jesse23023130123456789.54321 instead of the binary digits.

Where have I steered myself wrong on this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace BinaryData
{
    class Program
    {
        static void Main(string[] args)
        {
        string name = "Jesse";
        int courseNum = 230;
        int num = 23130;
        decimal d = 123456789.54321M;

        string combined = name + courseNum + num + d;

        FileStream writeStream;

        writeStream = new FileStream("BinaryData.dat", FileMode.Create);
        BinaryWriter bw = new BinaryWriter(writeStream);
        bw.Write(combined);
        }
    }
}
6
  • 3
    You're wanting 0's and 1's to be written to your file? Commented Aug 1, 2015 at 20:36
  • 1
    stackoverflow.com/a/655857/1870760 Commented Aug 1, 2015 at 20:37
  • duplicate: stackoverflow.com/questions/13502978/… Commented Aug 1, 2015 at 20:37
  • 1
    OK, but notepad shows text. not binary, so, a fille that contains text you wrote as bits, would still be text.. you just wrote it bit by bit.. @Shar1er80 has found you an answer Commented Aug 1, 2015 at 21:07
  • 2
    Please note that all text files are "binary" in the sense that they contain bytes. The fact that some files are considered text files is just a convention, a decision to interpret the bytes as text. Notepad follows that convention, so unless you write the text 1010101 to the file, a binary file will be opened as though it contained text. Commented Aug 1, 2015 at 21:22

2 Answers 2

2

There's more than one way to do this, but here's a basic approach. After you combine everything into a single string iterate through the string and convert each character into it's binary representation with Convert.ToString(char, 2). ASCII characters normally will be 7 bits or less in length, so you'll need to PadLeft(8, '0') to ensure 8 bits per byte. Then for the reverse you just grab 8 bits at a time and convert it back to its ASCII character. Without padding with leading 0's to ensure eight bits you won't be sure how many bits make up each character in the file.

using System;
using System.Text;

public class Program
{
    public static void Main()
    {
        string name = "Jesse";
        int courseNum = 230;
        int num = 23130;
        decimal d = 123456789.54321M;

        string combined = name + courseNum + num + d;

        // Translate ASCII to binary
        StringBuilder sb = new StringBuilder();
        foreach (char c in combined)
        {
            sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
        }

        string binary = sb.ToString();
        Console.WriteLine(binary);

        // Translate binary to ASCII
        StringBuilder decodedBinary = new StringBuilder();
        for (int i = 0; i < binary.Length; i += 8) 
        {
            decodedBinary.Append(Convert.ToChar(Convert.ToByte(binary.Substring(i, 8), 2)));
        }
        Console.WriteLine(decodedBinary);
    }
}

Results:

01001010011001010111001101110011011001010011001000110011001100000011001000110011001100010011001100110000001100010011001000110011001101000011010100110110001101110011100000111001001011100011010100110100001100110011001000110001
Jesse23023130123456789.54321

Fiddle Demo

Sign up to request clarification or add additional context in comments.

4 Comments

ASCII? No one asked for ASCII. .NET strings and chars are Unicode. Try it with "Jesse owes me €20". (Of course, the question doesn't specify an encoding but the code in the answer doesn't check its limitations.)
@TomBlodget Point taken. I assume ASCII with the sample data given in the question, if the character is beyond the range of ASCII characters then a delimiter will have to separate each character's binary.
To me the sample data contains a person's name. That could be Виктор Ан, 안현수, or Victor An. (All the same person, by the way.)
@TomBlodget Again, I understand your point. My answer does not take into account non-ASCII characters, but as you said the question doesn't specify an encoding.
-1

Here you go:

The main method:

static void Main(string[] args)
        {
            string name = "Jesse";
            int courseNum = 230;
            int num = 23130;
            decimal d = 123456789.54321M;

            string combined = name + courseNum + num + d;
            string bitString = GetBits(combined);
            System.IO.File.WriteAllText(@"your_full_path_with_exiting_text_file", bitString);
            Console.ReadLine();
        }

The method returns the bits, 0 and 1 based on your string input of-course:

   public static string GetBits(string input)
    {
        StringBuilder sb = new StringBuilder();
        foreach (byte b in Encoding.Unicode.GetBytes(input))
        {
            sb.Append(Convert.ToString(b, 2));
        }
        return sb.ToString();
    }

If you want to create the .txt file then add the code for it. This example has already a .txt created, so it just needs the full path to write to it.

3 Comments

Keep in mind that if you decided to read that data back in, you won't know how many bits make up each character.
BTW: Encoding.Unicode.GetBytes would return 2 bytes for each character. So for ab it would return 97,0,98,0 and your for-loop would append unnecessary 0's to the result. A terrible answer.
@EZI Encoding.Unicode.GetBytes (the UTF-16 encoding) would return 2 or 4 bytes per character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.