您的文件大小将为 2 字节(16 位)。您不能拥有大小为 10 位的文件(仅 8、16、24、32、40 ...)。在磁盘中,分配给文件的大小可以与簇大小一样小。如果磁盘上的簇大小为4096字节并且文件大小小于簇大小,则文件系统将分配簇大小的内存。
大小以字节为单位,所以如果你有字符串"00101"
(5 位)字节表示形式为00000101
(8 位)。
在你的情况下你的字符串是"0101110011"
(12 位)- 它是两个字节:
"01"
在字符串中将是00000001
以字节表示
"01110011"
在字符串中将是01110011
以字节为单位
表示
第二个字符串的长度为 8,因此字节将类似于该字符串。
你的字符串从'0'
但你可以省略'0'
它们一开始是没有用的。这意味着比字节表示值01110011
and 1110011
是相同的。
Hepler:
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;
}
另外,你应该使用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();
此外,此示例适用于不同的字符串长度。
从文件中读取值后,您将获得 2 个字节,然后将其转换为string
。但这些字节的字符串将是"0000000101110011"
(有不必要的'0'
在开始时)。
获取从以下位置开始的字符串'1'
:
string withoutZeroes =
withZeroes.Substring(withZeroes.IndexOf('1'), str.Length - withZeroes.IndexOf('1'));
所有操作之后(带字符串"0101110011"
)您的文件大小为 2 字节(16 位),但文件系统为其分配更多内存(分配的内存大小将等于簇大小)。