Вопрос

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) , а затем соединить эти две строки вместе и записать их в двоичный файл .

Редактировать :@dtb :простой пример может быть таким: value1 = "A" ,value2 = "B" и length1 = 8 и length2 = 16 , и результатом будет 010000010000000001000010 первые 8 бит взяты из "A", а следующие 16 бит - из "B".

Это было полезно?

Решение

        //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 (например, e в резюме), будет сбиваться с толку и, вероятно, вернет ASCII 63, который является вопросительным знаком.

Другие советы

При преобразовании строки во что-то другое вам нужно учитывать, какую кодировку вы хотите использовать.Вот версия, которая использует UTF-8

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

Редактировать Хм...увидел, что вы ищете BitArray, а не ByteArray, вероятно, это вам не поможет.

Поскольку это не очень четкий вопрос, я, тем не менее, попробую,

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static void RunSnippet()
{
   string 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("Serialized to test.bin");
   }
   Console.ReadLine();
}

Это то, чего вы пытаетесь достичь?

Надеюсь, это поможет, С наилучшими пожеланиями, Том.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top