Sudantha
Sudantha

Reputation: 16194

Binary To Corresponding ASCII String Conversion

Hi i was able to convert a ASCII string to binary using a binarywriter .. as 10101011 . im required back to convert Binary ---> ASCII string .. any idea how to do it ?

Upvotes: 10

Views: 43861

Answers (5)

Shadow Wizard
Shadow Wizard

Reputation: 66389

Sometimes instead of using the built in tools it's better to use "custom" code.. try this function:

public string BinaryToString(string binary)
{
    if (string.IsNullOrEmpty(binary))
        throw new ArgumentNullException("binary");

    if ((binary.Length % 8) != 0)
        throw new ArgumentException("Binary string invalid (must divide by 8)", "binary");

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < binary.Length; i += 8)
    {
        string section = binary.Substring(i, 8);
        int ascii = 0;
        try
        {
            ascii = Convert.ToInt32(section, 2);
        }
        catch
        {
            throw new ArgumentException("Binary string contains invalid section: " + section, "binary");
        }
        builder.Append((char)ascii);
    }
    return builder.ToString();
}

Tested with 010000010100001001000011 it returned ABC using the "raw" ASCII values.

Upvotes: 0

Chris Baxter
Chris Baxter

Reputation: 16353

This should do the trick... or at least get you started...

public Byte[] GetBytesFromBinaryString(String binary)
{
  var list = new List<Byte>();

  for (int i = 0; i < binary.Length; i += 8)
  {
    String t = binary.Substring(i, 8);

    list.Add(Convert.ToByte(t, 2));
  }

  return list.ToArray();
}

Once the binary string has been converted to a byte array, finish off with

Encoding.ASCII.GetString(data);

So...

var data = GetBytesFromBinaryString("010000010100001001000011");
var text = Encoding.ASCII.GetString(data);

Upvotes: 23

Alex Aza
Alex Aza

Reputation: 78447

If you have ASCII charters only you could use Encoding.ASCII.GetBytes and Encoding.ASCII.GetString.

var text = "Test";
var bytes = Encoding.ASCII.GetBytes(text);
var newText = Encoding.ASCII.GetString(bytes);

Upvotes: 7

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

Take this as a simple example:

public void ByteToString()
{
   Byte[] arrByte = { 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 };

   string x = Convert.ToBase64String(arrByte);
}

This linked answer has interesting details about this kind of conversion:

binary file to string

Upvotes: 1

Amit
Amit

Reputation: 22076

Here is complete code for your answer

FileStream iFile = new FileStream(@"c:\test\binary.dat",
FileMode.Open);

long lengthInBytes = iFile.Length;

BinaryReader bin = new BinaryReader(aFile);

byte[] byteArray = bin.ReadBytes((int)lengthInBytes);

System.Text.Encoding encEncoder = System.Text.ASCIIEncoding.ASCII;

string str = encEncoder.GetString(byteArray);

Upvotes: 3

Related Questions