How To Write A String Of Binary To File C#

China☆狼群 提交于 2020-03-22 01:50:03

问题


I Have A String Of Binary Number Like temp = "0101110011" And I Want To Save That As File this Temp Have 10 char And How Can I Save This string To file With 10 Bit Length ?

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();
}

With This Code My File Length Is 80 Bit's


回答1:


Your file size will be 2 bytes (16 bits). You can't have file with size 10 bits (only 8, 16, 24, 32, 40 ...). In disk the size allocated for file can be as small as cluster size. If cluster size on the disk is 4096 bytes and file size is less than cluster size, the file system will allocate memory of cluster size.

Sizes are in bytes, so if you have string "00101" (5 bits) in byte representation it will be 00000101 (8 bits).

In your case yor string is "0101110011" (12 bits) - it is two bytes:

  1. "01" in string that will be 00000001 in byte representation

  2. "01110011" in string that will be 01110011 in byte representation

Second string has length 8 so byte will look like this string.

Your string start from '0' but you can omit '0' they are unusefull at the beginning. It means than in byte representation values 01110011 and 1110011 are the same.

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;
}

Also, you should use BinaryWriter instead of 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();

Also, this example works for different string lengths.

After reading value from your file you will get 2 bytes which you then will convert into string. But the string from those bytes will be "0000000101110011" (with unnecessary '0' at the beginning).

To get string that starts from '1':

string withoutZeroes = 
       withZeroes.Substring(withZeroes.IndexOf('1'), str.Length - withZeroes.IndexOf('1'));

After all operations(with string "0101110011") your file will have size 2 bytes (16 bits) but file system allocates more memory for it (size of allocated memory will be equivalent to cluster size).




回答2:


length your string (which is representing 10 bits) of binary numbers is 10 and smallest data type is byte (8 bits). your data would be fit in two bytes as @Roma have suggested.

But here comes problem

your string is "0101110011"

and after his solution you will have two bytes as follow

00000001 and 01110011

so while getting them back from file and merging them together you will have string of 16 length "0000000101110011"

which is not your exact string.

So you would have to introduce one overhead, a header which will contain length of input string in last byte.

{
    Byte length //here 2
       Byte[] dataInBytes //here two byte 00000001 and 01110011
}


来源:https://stackoverflow.com/questions/41778077/how-to-write-a-string-of-binary-to-file-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!