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 的最快方法(如果字符串大于定义的长度并且如果字符串大小更小,则应修剪字符串,剩余位将填充为假),然后放入将这两个字符串放在一起并将其写入二进制文件。

编辑:@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);

编辑 嗯...看到你正在寻找一个 BitArray 而不是一个 ByteArray,这可能对你没有帮助。

于 2010-01-20T14:32:28.177 回答
0

由于这不是一个非常明确的问题,我还是会试一试,

使用 System.IO;
使用 System.Runtime.Serialization;
使用 System.Runtime.Serialization.Formatters.Binary;
公共静态无效 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();
   使用 (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 回答
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 回答