0
string value1 , value1 ;
int length1 , length2 ;
System.Collections.BitArray bitValue1 = new System.Collections.BitArray(Length1);
System.Collections.BitArray bitValue2 = new System.Collections.BitArray(Length2);

各文字列を定義された長さで BitArray に変換する最速の方法を探しています (定義された長さよりも大きい場合は文字列をトリミングする必要があり、文字列のサイズが小さい場合は残りのビットが false で埋められます)。この 2 つの文字列をまとめて、バイナリ ファイルに書き込みます。

編集: @dtb: 簡単な例は次のようになります value1 = "A" ,value2 = "B" and length1 =8 and length2 = 16 そして結果は 010000010000000001000010 になります 最初の 8 ビットは "A" から、次の 16 ビットは「B」から

4

3 に答える 3

0

文字列を他の文字列に変換するときは、使用するエンコーディングを検討する必要があります。これがUTF-8を使用するバージョンです

bitValue1 = System.Text.Encoding.UTF8.GetBytes(value1, 0, length1);

編集 うーん...あなたがByteArrayではなくBitArrayを探しているのを見ました、これはおそらくあなたを助けません。

于 2010-01-20T14:32:28.177 に答える
0
        //Source string
        string value1 = "t";
        //Length in bits
        int length1 = 2;
        //Convert the text to an array of ASCII bytes
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(value1);
        //Create a temp BitArray from the bytes
        System.Collections.BitArray tempBits = new System.Collections.BitArray(bytes);
        //Create the output BitArray setting the maximum length
        System.Collections.BitArray bitValue1 = new System.Collections.BitArray(length1);
        //Loop through the temp array
        for(int i=0;i<tempBits.Length;i++)
        {
            //If we're outside of the range of the output array exit
            if (i >= length1) break;
            //Otherwise copy the value from the temp to the output
            bitValue1.Set(i, tempBits.Get(i));                
        }

繰り返しますが、これは ASCII 文字を想定しているため、ASCII 127 を超えるもの (履歴書の é など) はびっくりして、疑問符である ASCII 63 を返す可能性があります。

于 2010-01-20T15:10:51.817 に答える
0

これはあまり明確な質問ではないので、それでも試してみます。

System.IO の使用;
System.Runtime.Serialization の使用;
System.Runtime.Serialization.Formatters.Binary を使用します。
public static void RunSnippet()
{
   文字列 s = "123";
   byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(s);
   System.Collections.BitArray bArr = new System.Collections.BitArray(b);
   Console.WriteLine("bArr.Count = {0}", bArr.Count);
   for(int i = 0; i < bArr.Count; i++)
    Console.WriteLin(string.Format("{0}", bArr.Get(i).ToString()));
   BinaryFormatter bf = new BinaryFormatter();
   using (FileStream fStream = new FileStream("test.bin", System.IO.FileMode.CreateNew)){
    bf.Serialize(fStream, (System.Collections.BitArray)bArr);
    Console.WriteLine("test.bin にシリアル化");
   }
   Console.ReadLine();
}

それはあなたが達成しようとしていることですか?

これがお役に立てば幸いです。よろしくお願いします、トム。

于 2010-01-20T14:59:17.363 に答える