String to Decimal to Binary Converter
In an effort to clutter the world with useless (but fun classes), I offer this up.
Seriously, I was looking for a quick way to come up with a clever (clever is debateable) IM name, I wrote this class that takes a string, converts it to a byte array and then returns back the binary representation (as a string). For example
Mathew is returned back as 01001101 01100001 01110100 01101000 01100101 01110111
Here is the class code
/// <summary>
/// Summary description for Base2Converter.
/// </summary>
public class Base2Converter
{
#region ctors
/// <summary>
/// The default constructor.
/// </summary>
public Base2Converter(){}
#endregion ctors
#region public methods
/// <summary>
/// Converts the string into a representative binary string.
///
/// This method converts each character to its ascii equivalent
/// and then creates a binary representation of its ascii value.
/// e.g. 'M' == 77 == 01001101.....
///
/// Note: This only converts ascii characters...oh well. its
/// a pretty useless (but fun) class anyway.
/// </summary>
/// <param name="val">Value to convert</param>
/// <returns></returns>
public string Convert( string val )
{
if( val == null ) return null;
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] byt = encoder.GetBytes( val );
StringBuilder retVal = new StringBuilder();
for(int i=0;i<byt.Length;i++)
{
// put a space b/w characters.
if( i > 0 ) retVal.Append( ' ' );
StringBuilder itemVal=new StringBuilder();
int convertedVal = (int)byt[i];
for(int k=7;k>=0;k--)
{
int power=(int)Math.Pow(2,k);
int remainder=convertedVal-power;
if(remainder>=0)
{
itemVal.Append( '1' );
convertedVal=remainder;
}
else
{
itemVal.Append( '0' );
}
}
retVal.Append( itemVal.ToString() );
}
return retVal.ToString();
}
#endregion public methods
}