Inv*_*Boy 5 c# bitarray binarywriter
我有一个像 temp = "0101110011" 这样的二进制数字符串,我想将它保存为文件,这个临时文件有 10 个字符,我如何将此字符串保存到 10 位长度的文件?
void Save_Data(string temp)
{
bool[] BoolArray = new bool[temp.Length];
BitArray Barray = new BitArray(BoolArray.Length);
char[] ch = temp.ToCharArray();
for (int i = 0; i < temp.Length; i++)
{
if (ch[i] == '0')
{
Barray[i] = false;
}
else
{
Barray[i] = true;
}
}
Stream stream = new FileStream("D:\\test.dat", FileMode.Create);
StreamWriter sw = new StreamWriter(stream);
foreach (bool bit in Barray)
{
sw.Write(bit ? 1 : 0);
}
sw.Flush();
sw.Close();
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,我的文件长度为 80 位
您的文件大小将为 2 字节(16 位)。您不能拥有 10 位大小的文件(只有 8、16、24、32、40 ...)。在磁盘中,为文件分配的大小可以与簇大小一样小。如果磁盘上的簇大小为 4096 字节且文件大小小于簇大小,则文件系统将分配簇大小的内存。
大小以字节为单位,所以如果你有"00101"字节表示的字符串(5 位),它将是00000101(8 位)。
在您的情况下,您的字符串是"0101110011"(12 位) - 它是两个字节:
"01"在将以00000001字节表示的 字符串中
"01110011"在将以01110011字节表示的字符串中
第二个字符串的长度为 8,因此字节看起来像这个字符串。
你的字符串从'0'但你可以省略'0'它们在开头是无用的。这意味着比以字节表示的值01110011和1110011是相同的。
赫普勒:
byte[] StringToBytesArray(string str)
{
var bitsToPad = 8 - str.Length % 8;
if (bitsToPad != 8)
{
var neededLength = bitsToPad + str.Length;
str = str.PadLeft(neededLength, '0');
}
int size= str.Length / 8;
byte[] arr = new byte[size];
for (int a = 0; a < size; a++)
{
arr[a] = Convert.ToByte(str.Substring(a * 8, 8), 2);
}
return arr;
}
Run Code Online (Sandbox Code Playgroud)
此外,您应该使用BinaryWriter代替StreamWriter:
string str = "0101110011";
byte[] arr = StringToBytesArray(str);
Stream stream = new FileStream("D:\\test.dat", FileMode.Create);
BinaryWriter bw = new BinaryWriter(stream);
foreach (var b in arr)
{
bw.Write(b);
}
bw.Flush();
bw.Close();
Run Code Online (Sandbox Code Playgroud)
此外,此示例适用于不同的字符串长度。
从文件中读取值后,您将获得 2 个字节,然后将其转换为string. 但是这些字节中的字符串将是"0000000101110011"('0'开头不需要)。
获取从 开始的字符串'1':
string withoutZeroes =
withZeroes.Substring(withZeroes.IndexOf('1'), str.Length - withZeroes.IndexOf('1'));
Run Code Online (Sandbox Code Playgroud)
在所有操作(使用 string "0101110011")之后,您的文件的大小将是 2 字节(16 位),但文件系统会为其分配更多内存(分配的内存大小将等于集群大小)。