How To Write A String Of Binary To File C#

InvBoy picture InvBoy · Jan 21, 2017 · Viewed 9.5k times · Source

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

Answer

Roman Doskoch picture Roman Doskoch · Jan 21, 2017

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).