二进制到对应的ASCII字符串转换

时间:2011-05-15 04:12:04

标签: c#

您好我能够使用ASCII ..将binarywriter字符串转换为二进制文件为10101011。我需要回来转换Binary ---> ASCII字符串..任何想法怎么做?

5 个答案:

答案 0 :(得分:21)

这应该可以解决问题......或者至少让你开始......

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

二进制字符串转换为字节数组后,用

结束
Encoding.ASCII.GetString(data);

因此...

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

答案 1 :(得分:6)

如果您只有ASCII章程,则可以使用Encoding.ASCII.GetBytesEncoding.ASCII.GetString

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

答案 2 :(得分:2)

以下是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);

答案 3 :(得分:1)

以此为例:

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

   string x = Convert.ToBase64String(arrByte);
}

这个链接的答案有关于这种转换的有趣细节:

binary file to string

答案 4 :(得分:0)

有时候不使用内置工具,最好使用“自定义”代码。试试这个功能:

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

使用010000010100001001000011进行测试后,它使用“原始”ASCII值返回ABC