[英]save string array in binary format
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”
将字符串转换为其他字符串时,需要考虑要使用的编码。 这是使用UTF-8的版本
bitValue1 = System.Text.Encoding.UTF8.GetBytes(value1, 0, length1);
Edit Hmm ...看到您在寻找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(); }
那是您要达到的目标吗?
希望这对您有所帮助,汤姆,谢谢。
//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的任何内容(例如éinrésumé)都将出现异常,并可能返回问号ASCII 63。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.