2011-06-08 87 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