【问题标题】:C# binary to stringC#二进制转字符串
【发布时间】:2011-06-09 07:20:38
【问题描述】:

我正在使用string messaga = _serialPort.ReadLine(); 从串口读取数据 当 i Console.WriteLine(messaga); 随机字符出现在屏幕上时,这是合乎逻辑的,因为二进制数据不是 ASCII。 我想我使用的方法将数据处理为 ascii。 我想做的是创建一个字符串 var 并将来自端口的二进制原始数据分配给它,所以当我 console.write 这个 var 时,我想看到一个带有二进制数据的字符串,如 1101101110001011010 而不是字符。我该如何处理?

【问题讨论】:

  • 你有显示“字符”的例子吗?
  • 你真的期望它将所有位转换为 10100010 等字符串吗?
  • _serialPort 是否有读取byte[]String 的方法?如果您想打印这些位,似乎最好使用该方法。
  • 我们不是为了名声而来,但我们想知道我们的解决方案是否正确!以及什么是修正自己的最佳解决方案
  • @Mike Miller - 没有那样的 :)- 当人们是新来的时候,这是可以理解的,因为在这方面它与“普通”论坛完全不同。

标签: c# string byte bin


【解决方案1】:

盗自How do you convert a string to ascii to binary in C#?

foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
{
  Console.WriteLine(letter);
}

【讨论】:

  • -1 因为没有正确处理。 Convert.ToString(c,2) 的结果没有用前导零填充到类型的正确宽度(例如,(byte)0x01 的转换产生 "1" 而不是 "00000001")。
【解决方案2】:

你的意思是这样的?

class Utility
{
  static readonly string[] BitPatterns ;
  static Utility()
  {
    BitPatterns = new string[256] ;
    for ( int i = 0 ; i < 256 ; ++i )
    {
      char[] chars = new char[8] ;
      for ( byte j = 0 , mask = 0x80 ; mask != 0x00 ; ++j , mask >>= 1 )
      {
        chars[j] = ( 0 == (i&mask) ? '0' : '1' ) ;
      }
      BitPatterns[i] = new string( chars ) ;
    }
    return ;
  }

  const int BITS_PER_BYTE = 8 ;
  public static string ToBinaryRepresentation( byte[] bytes )
  {
    StringBuilder sb = new StringBuilder( bytes.Length * BITS_PER_BYTE ) ;

    foreach ( byte b in bytes )
    {
      sb.Append( BitPatterns[b] ) ;
    }

    string instance = sb.ToString() ;
    return instance ;
  }

}
class Program
{
  static void Main()
  {
    byte[] foo = { 0x00 , 0x01 , 0x02 , 0x03 , } ;
    string s   = Utility.ToBinaryRepresentation( foo ) ;
    return ;
  }
}

刚刚对此进行了基准测试。上面的代码比使用Convert.ToString() 快大约 12 倍,如果将校正添加到带有前导 '0' 的填充,则大约快 17 倍。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-05
    • 2011-07-11
    • 2017-02-23
    • 2014-08-03
    • 2010-09-25
    • 2014-06-14
    • 2017-03-22
    • 1970-01-01
    相关资源
    最近更新 更多