3

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

File.WriteAllText(path, str);

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

user4775372
  • 87
  • 1
  • 5
  • Sure. You have to go 8 bits at a time, parse the number (either manually, or using `Convert.ToByte(substr, 2)`, and write the bytes you get like this. You're trying to write a binary file, so it shouldn't be surprising that writing a text file doesn't work :) – Luaan May 07 '15 at 15:25
  • @AlexK. I think he just means he can have multiple bytes on output - 2, 4, 6... But the input string is still just a string of binary digits. – Luaan May 07 '15 at 15:26

1 Answers1

0

You can try something like this. This works with the 16 bits you posted. If you have more, you may wish to read them 32 bits at a time and convert. But this 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);
    }
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48