Revisited---String to Decimal to Binary Converter

In a previous post, I posted a piece of code that would convert a string to its decimal equivalent and then its binary equivalent. For example:

Mathew is returned back as 01001101 01100001 01110100 01101000 01100101 01110111

A very good comment pointed out that i can just use Convert.ToString() method. I have used this class extensively but I never noticed the versions that converts either a byte, int16 or int32 to different numeric bases (e.g. base 2). I will cut myself a bit of slack because there are 36 different overridden versions of Convert.ToString(), but its a nice feature and well worth pointing out. Furthermore, it reduces the size of my code considerably(see below). Also, I could probably have made the code a bit more generic, but at the end of the day the class is still pretty useless (I just wanted to come up with a way to create clever IM display names)...so why bother ;-)

///


/// Summary description for Base2Converter.
///

public class Base2Converter
{
        #region ctors
        ///
        /// The default constructor.
        ///

        public Base2Converter(){}
        #endregion ctors

        #region public methods
        ///


        /// Converts the string into a representative binary string.
        ///

        /// Value to convert
        ///
        public string Convert( string val )
        {
                if( val == null ) return null;
                StringBuilder retVal=new StringBuilder();
               
foreach
(char c in val)
                {
                       // put a space b/w each character...
                       
if
(retVal.Length>0) retVal.Append(' ');
                        retVal.Append( Convert.ToString( c,2 ) );
                }
                return retVal.ToString();
        }
        #endregion public methods
}

2 Comments

  • I am trying to restrict drive access by changing the system.adm file,, I have to create a new string to support "F" how do you use the converter to find the binary string and the decimal string of F???



    Thanks,

    Jon



    Jerdos8@hotmail.com

  • I am trying to restrict drive access by changing the system.adm file,, I have to create a new string to support "F" how do you use the converter to find the binary string and the decimal string of F???



    Thanks,

    Jon



    Jerdos8@hotmail.com

Comments have been disabled for this content.