Mohamed Abdelfattah
Mohamed Abdelfattah

Reputation: 13

Character Textfile to binary Textfile

I have a text file that contains a set of records and i am trying to convert and save it as 1's and 0's .. every time I use

Byte [] arr=Encoding.UTF8.GetBytes(recordss) ;

and write it using a byte writer i still have to same record file with no difference.

So my question is there a way to convert a string to binary and write it to a file in binary format. I am using c# by the way

Here is my code so far

public static void serialData()
{
    FileStream recFile = new FileStream("Records.txt", FileMode.Open, FileAccess.ReadWrite);   //file to be used for records

    StreamReader recordRead = new StreamReader(recFile);

    String recordss = recordRead.ReadToEnd();        //Reads Record file

    recordRead.Close();
    recFile.Close();

    Byte [] arr=Encoding.UTF8.GetBytes(recordss) ;

    FileStream file = new FileStream("Temp.txt", FileMode.Create, FileAccess.Write);
    StreamWriter binfile = new StreamWriter(file);

    for(int i =0; i < arr.Count();i++)
        binfile.WriteLine(arr[i]);

    binfile.Close();
    file.Close();
}

Upvotes: 1

Views: 1722

Answers (2)

likeitlikeit
likeitlikeit

Reputation: 5638

There's a built-in function to convert from integer-type values to strings with binary representation. Try replacing the line

binfile.WriteLine(arr[i]);

by this line

binfile.WriteLine(
    Convert.ToString(arr[i], 2)
);

Convert.ToString() will convert the input to a representation in the given base. In this case, you choose 2 as base for a binary representation. Other common values would be 8 for octal, or 16 for hexadecimal.

Upvotes: 1

Askolein
Askolein

Reputation: 3378

Your result is in 'byte' format. Always. By definition it is data. The way you 'see' it depends on the software you use to open it.

What you want is probably a file that when openned in a text editor 'shows' the underlying binary data of your original data source: as text. For this you'll have to write in the file as character '0' and '1'. Therefore, the final file will be a lot bigger thant the original data source.

Change this code:

for(int i =0; i < arr.Count();i++)
    binfile.WriteLine(arr[i]);

Into this:

foreach (byte b in arr)
{
    binfile.Write((b >> 7 & 1) == 0 ? '0' : '1');
    binfile.Write((b >> 6 & 1) == 0 ? '0' : '1');
    binfile.Write((b >> 5 & 1) == 0 ? '0' : '1');
    binfile.Write((b >> 4 & 1) == 0 ? '0' : '1');
    binfile.Write((b >> 3 & 1) == 0 ? '0' : '1');
    binfile.Write((b >> 2 & 1) == 0 ? '0' : '1');
    binfile.Write((b >> 1 & 1) == 0 ? '0' : '1');
    binfile.Write((b & 1) == 0 ? '0' : '1');
}

But it is kind of ugly. Better use an hexadecimal file viewer.

Upvotes: 0

Related Questions