Click here to Skip to main content
15,896,915 members
Articles / Programming Languages / C#
Article

Binary String Manipulation

Rate me:
Please Sign up or sign in to vote.
3.92/5 (6 votes)
11 Dec 20063 min read 84.5K   969   28   7
An article to demonstrate conversion of a string to binary and manipulation thereof.

Sample Image

Introduction

This article looks at the conversion of a string to a binary stream and the conversion of a BitArray of binary data to an ASCII string. The .NET Framework does not provide a method for constructing a byte of data by explicitly specifying each bit. This makes it difficult to convert a string containing binary data back into ASCII encoded data, which is a useful exercise in some debugging scenarios.

Using the code

Let us first look at converting a string into binary. We do this using the MemoryStream and BinaryWriter objects. The BinaryWriter object allows us to write a stream of binary data for a given string. As we are not sending the binary data anywhere (in this example), we will use a MemoryStream object to provide us with a stream to use.

C#
MemoryStream ms_memStream = new MemoryStream();
BinaryWriter br_binaryWriter = new BinaryWriter(ms_memStream);

try
{
    br_binaryWriter.Write(ba_originalString);
}
catch (Exception e)
{
    System.Console.WriteLine("Exception writing binary" + 
                             " data to memory stream: " + 
                             e.Message);
    Environment.Exit(1);
}

The BinaryWriter.Write(String str) method converts the string parameter into a stream of binary data that is stored in the associated stream object, in this case our MemoryStream object. It is important to note that because the data has been serialized, the bytes of data within the binary stream no longer have the most significant bit on the left, so the letter "T" would be 00101010 (ASCII 84) instead of 01010100. It is very important to bear this in mind when reading the data later, as, if we do not account for this, we will not read the value correctly. In this case, we would interpret the data as ASCII value 42, which is not the letter "T".

Converting a binary stream back into ASCII can be done in several ways depending upon what form we have the binary data in. The simplest method is where we have the binary data as a stream, as shown above. This method is useful if the binary data is being read from a file. To do this, we simply use the following code:

C#
String str_recoveredString = 
    Encoding.ASCII.GetString(ms_memStream.ToArray());

If we want to look at the bits in the stream one by one, we must convert the binary data into a BitArray object, as shown here:

C#
BitArray ba_bitArray = new BitArray(ms_memStream.ToArray());

N.B. The need for this was encountered by the author by using a stream of binary data for encryption purposes. This required looking at individual bits in a key string to generate a unique salt from it.

Once a binary stream is encapsulated by a BitArray object, it becomes slightly more difficult to manipulate. None of the traditional conversion/parsing methods work, as a BitArray object only returns values as Booleans. Furthermore, the .NET Framework does not provide a method for creating a byte object by explicitly setting the values of each bit within it. Thus, to convert binary data within a BitArray object back into ASCII, we must calculate the decimal values from the binary data, as shown here:

C#
private static string recoverText(BitArray ba_bitArray)
{
    string str_finalString = "";

    int int_binaryValue;

    BitArray ba_tempBitArray;

    // Manually read the first 8 bits and
    while (ba_bitArray.Length > 0)
    {
        ba_tempBitArray = new BitArray(ba_bitArray.Length - 8);
        int_binaryValue = 0;

        if (ba_bitArray[0])int_binaryValue += 1;
        if (ba_bitArray[1]) int_binaryValue += 2;
        if (ba_bitArray[2]) int_binaryValue += 4;
        if (ba_bitArray[3]) int_binaryValue += 8;
        if (ba_bitArray[4]) int_binaryValue += 16;
        if (ba_bitArray[5]) int_binaryValue += 32;
        if (ba_bitArray[6]) int_binaryValue += 64;
        if (ba_bitArray[7]) int_binaryValue += 128;

        str_finalString += Char.ConvertFromUtf32(int_binaryValue);
        int int_counter = 0;
        for (int i = 8; i < ba_bitArray.Length; i++)
        {
               ba_tempBitArray[int_counter++] = ba_bitArray[i];
        }
           ba_bitArray = ba_tempBitArray;
    }
    return str_finalString;
}

Here we are simply converting 8 bits of binary to decimal and using the Char.ConvertFromUtf32(int i) method to return a String object of the appropriate ASCII value. We do this for each block of eight bits in the BitArray and then return the string.

History

  • Initially written: 10th October 2006.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionA mismatch in values? Pin
chaos56877-Aug-10 0:06
chaos56877-Aug-10 0:06 
GeneralProblem with Encode/Recode to memstream Pin
hjgode8-Nov-07 3:16
hjgode8-Nov-07 3:16 
GeneralRe: Problem with Encode/Recode to memstream Pin
Rolf Baxter16-Nov-07 3:25
Rolf Baxter16-Nov-07 3:25 
GeneralRe: Problem with Encode/Recode to memstream Pin
hjgode16-Nov-07 3:46
hjgode16-Nov-07 3:46 
GeneralThanks for the code! Pin
Joseph V17-Sep-07 9:38
Joseph V17-Sep-07 9:38 
Generalis it .NET 1.1 or 2.0 sample Pin
sharad_sharma_2k8-Feb-07 21:20
sharad_sharma_2k8-Feb-07 21:20 
GeneralRe: is it .NET 1.1 or 2.0 sample Pin
Rolf Baxter14-Feb-07 4:30
Rolf Baxter14-Feb-07 4:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.