我正在從串行端口使用string messaga = _serialPort.ReadLine();
當我Console.WriteLine(messaga);
隨機字符出現在屏幕上,因爲二進制數據是非ASCII的邏輯。 我想我正在使用的方法處理數據ascii。 我想要做的是創建一個字符串變種,併爲它分配來自端口的二進制原始數據,所以當我console.write這個變種我想看到一個字符串與二進制數據,如1101101110001011010和NOT字符。我該如何管理?C#二進制到字符串
回答
被盜,你的意思是這樣嗎?
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倍。
從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);
}
並稱盜竊,其更多的是我認爲的引文。 – 2011-06-08 22:28:11
+1盜竊 – 2011-06-08 22:29:39
-1因爲不正確。 'Convert.ToString(c,2)'的結果沒有用前導零填充到類型的正確寬度(例如'(byte)0x01'的轉換產生'「1」'而不是'「00000001」 )。 – 2011-06-08 22:52:50
- 1. 字符串到二進制[]
- 2. 十六進制字符串到二進制字符串
- 3. Ruby:十六進制字符串到二進制字符串
- 4. Java |二進制字符串到字節
- 5. Json_encode二進制字符串
- 6. 字符串爲二進制
- 7. Flex二進制字符串到ByteArray
- 8. 從字符串到二進制列表
- 9. 二進制字符串到整數
- 10. 二進制搜索樹到字符串
- 11. Ruby整數到二進制字符串
- 12. 將二進制字符串轉換爲十進制c字符串#
- 13. 十六進制到二進制到字符串
- 14. 將二進制長字符串轉換爲十六進制c#
- 15. 如何通過LUA字符串(二進制)到C++使用tolua ++
- 16. 字符串寫入到二進制文件用C
- 17. PHP:符號二進制字符串
- 18. Java十進制到二進制沒有API和字符串
- 19. C++二進制輸入作爲一個字符串到十進制
- 20. MySQL比較二進制排序與二進制字符串
- 21. Python將二進制字符串轉換爲二進制int
- 22. 寫的字符串二進制數據的二進制文件
- 23. WPF C#字符串轉換爲十進制,十進制到字符串問題
- 24. Python讀取二進制文件中的二進制數據到字符串?
- 25. C++將字節二進制值轉換爲字符串
- 26. 將字節轉換爲c中的二進制字符串#
- 27. C++中的字節[]的二進制字符串?
- 28. 二進制文件字符串
- 29. 默認Erlang二進制字符串
- 30. 字符串二進制轉換
你有沒有顯示「字符」的例子? – 2011-06-08 21:55:30
你真的期望它將所有的位轉換爲10100010等字符串嗎? – BugFinder 2011-06-08 21:58:37
我們真的在這裏只是爲了聲望計數嗎? – 2011-06-08 22:02:47