How To Write A String Of Binary To File C#
Asked Answered
M

2

8

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

Monumentalize answered 21/1, 2017 at 10:10 Comment(7)
Do you want file with text 0101110011 with size 10 bits?Neonatal
@Roma No I Want To Save That As .dataMonumentalize
do you expect that saving "10101010" into a file will produce at the end 1 byte sized file??Archaeozoic
@ΦXocę웃Пepeúpaツ yesMonumentalize
what you are asking - file in which you have stored string of length of 10, and it will be 10 bits in size. It will not be possible. Minimum size it will take is 2 Bytes (16 bits) with no data lossBilletdoux
the file will use at least 1K disk space either way superuser.com/questions/1030800/…Tetragrammaton
@Slai, space allocated for file depends on cluster size. If cluster size is 4096 bytes then all files with size less than 4096 bytes will take 4KB space. It is not always 1KBNeonatal
N
6

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

Neonatal answered 21/1, 2017 at 10:46 Comment(1)
you are missing usings using(Stream stream = new FileStream("D:\\test.dat", FileMode.Create)) using(BinaryWriter bw = new BinaryWriter(stream))Autogenesis
B
1

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
}
Billetdoux answered 21/1, 2017 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.