string messaga = _serialPort.ReadLine();
When i random characters appear on the screen を使用してシリアル ポートから読み取ってConsole.WriteLine(messaga);いますが、これはバイナリ データが非 ASCII であるため論理的です。私が使用している方法は、データを ascii として処理すると思います。私がしたいのは、文字列変数を作成し、ポートからのバイナリ生データを割り当てることです。この変数を console.write すると、1101101110001011010 のようなバイナリ データと NOT 文字を含む文字列が表示されます。どうすればそれを管理できますか?
1953 次
2 に答える
5
盗まれたC#で文字列をASCIIからバイナリに変換するにはどうすればよいですか?
foreach (string letter in str.Select(c => Convert.ToString(c, 2)))
{
Console.WriteLine(letter);
}
于 2011-06-08T21:58:25.293 に答える
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 倍高速になります。
于 2011-06-08T22:30:41.187 に答える