Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary To Corresponding ASCII String Conversion

Tags:

c#

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 ?

like image 777
Sudantha Avatar asked May 15 '11 04:05

Sudantha


3 Answers

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);
like image 38
Chris Baxter Avatar answered Oct 19 '22 09:10

Chris Baxter


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);
like image 94
Alex Aza Avatar answered Oct 19 '22 09:10

Alex Aza


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);
like image 37
jams Avatar answered Oct 19 '22 09:10

jams