How can I save a string contains 1 and 0 to a bin file?

Hi, my string str = "1010101010101010" comes from file.txt which contains exactly 16 characters: 0 and 1. This is just an example and str can have more than 16 characters: 8,16,24,32,40 .. I want to save it to file.bin. After saving, file.bin should be 2B in size (in this example). I tried to use

File.WriteAllText(path, str);

      

but my file is bigger than i want. Can anyone help me?

+3


source to share


1 answer


You can try something like this. This works with the 16 bits you posted. If you have more, you can read them 32 bits at a time and convert. But that should get you started.



void Main()
{
    string path = @"g:\test\file.bin";
    string str="1010101010101010";

    //Convert string with 16 binary digits to a short (2 bytes)
    short converted = Convert.ToInt16(str, 2);

    //Convert the short to a byte array
    byte[] bytes = BitConverter.GetBytes(converted);

    //Write the byte array to a file
    using (var fileOut = new System.IO.FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
    {
        fileOut.Write(bytes, 0, bytes.Length);
    }
}

      

0


source







All Articles