Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Extension Me Convert: A Binary Look at System.IConvertible Derivations

0.00/5 (No votes)
14 Mar 2012CPOL3 min read 7.5K  
Extension Me Convert: A Binary Look at System.IConvertible Derivations

Welcome to another article for the Extension Me series. This series focuses on various uses of the .NET Framework feature: Extension Methods. This entry will focus on extending System.IConvertible objects to retrieve its binary form as a String. Basic knowledge of programming in C# and creating extension methods is assumed.

Converting from one data type to another (Casting) is quite commonplace in computer programming. In C#, this can be done in various ways:

  1. Implicit Casting
  2. Explicit Casting
  3. Using System.Convert

The list above will be described in the following three sections.

Implicit Casting

This is one of the most basic forms. When one variable of one data type is assigned to another with a different yet compatible data type, they can be implicitly cast. Here is an example:

C#
long lngValue = 9223372036854775806L;
int intValue = 2147483646;
lngValue = intValue;

Above is an example of implicit casting. A long (Int64) variable occupies 64 bits (or 8 bytes, or 16 nibbles). An int (Int32) variable occupies 32 bits (or 4 bytes, or 8 nibbles). Since Int32 memory space can easily fit within Int64 memory space (as depicted below), an implicit conversion can be applied from Int32 to Int64. An explicit cast must be performed when converting the opposite direction (Int64 to Int32) where truncation will occur.

A visual comparison between Int32 and Int64 memory space
Above is a visual comparison between Int32 and Int64 memory space (Int32 to Int64 cast).

Explicit Casting

This is another basic form of casting. Here is an example:

C#
long lngValue = 2147483646L;
int intValue = 0;
intValue = (int)lngValue;

Above is an example of explicit casting. Since a 64-bit variable does not completely fit within a 32-bit memory space, we must use explicit casting while accepting the fact truncation may occur (possibly loss of data). Truncation is depicted below (an Int64 to Int32 cast):

an Int64 to Int32 cast

Using System.Convert

System.Convert contains many methods meant to convert from one base data type to another. There are methods such as ToInt64, ToByte, ToDateTime, etc. Here is an example:

C#
int intValue = 2147483646;
long value = Convert.ToInt64(intValue);

Above is an example using the ToInt64 method of System.Convert. The method accepts the Int32 value we initialized and converts it to Int64. This particular method simply wraps an explicit cast: (long)value. Others are dependent on an object’s implementation of the System.IConvertible interface as shown in the implementation of the Convert.ToInt64(object) method:

C#
public static long ToInt64(object value)
{
    if (value != null)
    {
        return ((IConvertible) value).ToInt64(null);
    }
    return 0L;
}

Above is the implementation of Convert.ToInt64(object). The ToInt64 method of value is called after converting it to System.IConvertible proving its dependence on System.IConvertible objects.

The Extension

Now that we have gone over the basics of casting and the dependency on System.IConvertible objects, the extension method can be created. Below is the implementation:

C#
public static class IConvertibleToBinaryString
{
   public static String ToBinaryString(this IConvertible @this)
   {
      long value = Convert.ToInt64(@this, CultureInfo.InvariantCulture);
      String converted = Convert.ToString(value, 2);
      return converted;
   }
}

Above is the implementation of the extension method to convert objects deriving from System.IConvertible to their binary form as a String. First, the object is converted to long. This must be done to be able to specify the base for the Convert.ToString method that follows. The culture information provided is optional. Convert.ToString accepts a value to convert of type long and an integer specifying the base. This is important. Base 2 is binary, therefore, calling Convert.ToString(lngValue, base) with 2 as the base indicates a conversion to the binary form of the long value. There are other bases that can be used as well to create methods such as:

  1. ToHexString (use base 16)
  2. ToOctetString (use base 8)
  3. ToDecimalString (use base 10)

Proving Binary Validity

How does one know that the method actually works? Unit-testing is how! Below is a basic method testing four uses of the extension method previously created. This uses MSTest:

C#
public void ToBinaryFromLong()
{
   long lv = 10L;
   Assert.AreEqual("1010", lv.ToBinaryString());

   short sv = 2;
   Assert.AreEqual("10", sv.ToBinaryString());

   Boolean bln = true;
   Assert.AreEqual("1", bln.ToBinaryString());

   bln = false;
   Assert.AreEqual("0", bln.ToBinaryString());
}

Running the code above should pass. This means the binary form is retrieved as expected.

Conclusion

This entry provided a look at a combination of System.Convert, System.IConvertable, and extension methods. Please note: This entry demonstrated extending System.IConvertible objects. It is not to suggest a String of binary numbers has common relevant uses. This is an enjoyable entry meant to prove it can be done.


Filed under: .Net, C#, Extension Me, Extension Methods
Tagged: C#, Casting, Explicit, Extension Me, IConvertible, Implicit, implicit conversion, int64, memory space, Theory Image 3 Image 4 Image 5 Image 6 Image 7 Image 8 Image 9 Image 10

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)