Jesse Cleary
Jesse Cleary

Reputation: 123

C# Writing Binary Data

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);
        }
    }
}

Upvotes: 0

Views: 8061

Answers (2)

Shar1er80
Shar1er80

Reputation: 9041

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

Upvotes: 2

EugenSunic
EugenSunic

Reputation: 13733

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.

Upvotes: -1

Related Questions