2011-06-08 65 views
0

我正在从串行端口使用string messaga = _serialPort.ReadLine(); 当我Console.WriteLine(messaga);随机字符出现在屏幕上,因为二进制数据是非ASCII的逻辑。 我想我正在使用的方法处理数据ascii。 我想要做的是创建一个字符串变种,并为它分配来自端口的二进制原始数据,所以当我console.write这个变种我想看到一个字符串与二进制数据,如1101101110001011010和NOT字符。我该如何管理?C#二进制到字符串

+0

你有没有显示“字符”的例子? – 2011-06-08 21:55:30

+0

你真的期望它将所有的位转换为10100010等字符串吗? – BugFinder 2011-06-08 21:58:37

+0

我们真的在这里只是为了声望计数吗? – 2011-06-08 22:02:47

回答

0

被盗,你的意思是这样吗?

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倍。

5

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

并称盗窃,其更多的是我认为的引文。 – 2011-06-08 22:28:11

+1

+1盗窃 – 2011-06-08 22:29:39

+1

-1因为不正确。 'Convert.ToString(c,2)'的结果没有用前导零填充到类型的正确宽度(例如'(byte)0x01'的转换产生'“1”'而不是'“00000001” )。 – 2011-06-08 22:52:50