Channels ▼

Community Voices

Dr. Dobb's Bloggers

Convert from long to any number base in C#

April 04, 2008

Here is a C# .NET class that will convert a long value into any number base (2 to 32767) that you desire with mimanal work.

ConverterBase is an abatract base class that defines two methods for classes that derrive from ConverterBase to implement:

  • public Convert( long number ) is the only public method we need and simply calls base Convert passing the number and numberBase values
  • protected ConvertBase( long number int numberbase ) is nothing more than a switch statment that converts values to thier string representation in our number base

// A full set of classes to covert a long number to base 13, 2, 8, and 16 

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace Converters 
{
  // ConverterBase does all of the hard work and has twio abstract members
  //  for classes to implment
  public abstract class ConverterBase 
  {     public abstract string Convert( long number );

    protected string Convert( long number, int numberBase ) 
    { 
      StringBuilder sb = new StringBuilder(); 

      // this is just a crude attempt to get close to Pow( numberBase, i ) that is
      // less than our long number 
      int multiplier = ( numberBase > 10 ) ? number.ToString().Length + 5 
                                                           : (int) ( ( number / (long) numberBase ) + 5 );       long temp = -number; // negative because our for loop requires it


      int maxPower = 0;      // this for loop is where we find the maxPower of
                                      // numberBase that is
                                      // less than our long number
      for ( int i = multiplier; ( i > 0 ) && ( temp < 0 ); --i ) 
      { 
        temp = number - (long) Math.Pow( numberBase, i ); 
        maxPower = i; 
      } 
 
      // here is where we do the actual conversion to numberBase
      for ( int i = maxPower; i >= 0; --i ) 
      { 
        int quotent = (int) ( number / (long) Math.Pow( numberBase, i ) );
        number = number % (long) Math.Pow( numberBase, i ); 
        sb.Append( ConvertBase( quotent, numberBase ) ); 
      }
 
      // we trim any leading zeros from the start of the converted value
      return sb.ToString().TrimStart( '0' ); 
    }     protected abstract string ConvertBase( int number, int numberBase ); 
  } 

  // Converter implments a fictional base 13 number system
  public class Converter : ConverterBase 
  { 
    public override string Convert( long number ) 
    { 
      // we simply need to call ConverterBase::Convert and pass in the base of our
      // number system
      return Convert( number, 13 ); 
    }     // ConvertBase is nothing more than a switch statment that convert a number 
    // smaller than your numberBase to it string value in your numberBase
    protected override string ConvertBase( int number, int numberBase ) 
    {
       switch ( number % numberBase )
      {
         case 0: return "0";
         case 1: return "1";
         case 2: return "2"; 
         case 3: return "3";
         case 4: return "4";
         case 5: return "5";
         case 6: return "6";
         case 7: return "7";
         case 8: return "8";
         case 9: return "9";
         case 10: return "x";
         case 11: return "y";
         case 12: return "z";
         default: return "";
      }
    } 
  } 

  // BinaryConverter implments a Binary number system 
  public class BinaryConverter : ConverterBase 
  { 
    public override string Convert( long number ) 
    { 
      // call ConverterB ase::Convert and tell it that we are converting to Binary values
      return Convert( number, 2 ); 
    } 

    // Convert binary digits to their string values
    protected override string ConvertBase( int number, int numberBase ) 
    {
        switch ( number % numberBase )
       {
         case 0: return "0";
         case 1: return "1";
         default: return "";
       } 
    } 
  }   // OctalConverte imlments an Octal number system
  public class OctalConverter : ConverterBase 
  { 
    public override string Convert( long number ) 
    { 
      // call ConverterBase and tell it that we are converting to Octal values
      return Convert( number, 8 ); 
    } 

    // convert Octal values into their string values
    protected override string ConvertBase( int number, int numberBase )
    {
       switch ( number % numberBase ) 
      { 
        case 0: return "0"; 
        case 1: return "1"; 
        case 2: return "2"; 
        case 3: return "3"; 
        case 4: return "4"; 
        case 5: return "5"; 
        case 6: return "6"; 
        case 7: return "7"; 
        default: return ""; 
      } 
    } 
  }   // HexConverter implements a Hex number system
  public class HexConverter : ConverterBase 
  { 
    public override string Convert( long number ) 
    { 
      // Call ConverterBase and tell it we are converting to Hex values
      return Convert( number, 16 ); 
    } 

    // Convert Hex values to their string values
    protected override String ConvertBase ( int number, int numberBase ) 
    {
       switch ( number % numberBase ) 
       { 
         case 0: return "0"; 
         case 1: return "1"; 
         case 2: return "2"; 
         case 3: return "3"; 
         case 4: return "4"; 
         case 5: return "5"; 
         case 6: return "6"; 
         case 7: return "7"; 
         case 8: return "8"; 
         case 9: return "9"; 
         case 10: return "a"; 
         case 11: return "b"; 
         case 12: return "c"; 
         case 13: return "d"; 
         case 14: return "e"; 
         case 15: return "f"; 
         default: return ""; 
      } 
    } 
  }   // TestPogram is a command line program for testing our Converters
  public class TestProgram 
  { 
    static void Main() 
    { 
       // let's test our Converter class
|      Converter c = new Converter(); 

      Console.WriteLine( "{0} converts to {1}", 5, c.Convert( 5 ) ); 
      Console.WriteLine( "{0} converts to {1}", 10, c.Convert( 10 ) ); 
      Console.WriteLine( "{0} converts to {1}", 13, c.Convert( 13 ) ); 
      Console.WriteLine( "{0} converts to {1}", 20, c.Convert( 20 ) ); 
      Console.WriteLine( "{0} converts to {1}", 5006, c.Convert( 5006 ) ); 
      Console.WriteLine( "{0} converts to {1}", 9999999, c.Convert( 9999999 ) ); 

      Console.WriteLine(); 

      // let's test our BinaryConverter class
      BinaryConverter b = new BinaryConverter(); 

      Console.WriteLine( "{0} binary converts to {1}", 1024, b.Convert( 1024 ) ); 

      // let's test our OctalConverter class
      OctalConverter o = new OctalConverter();       Console.WriteLine( "{0} octal converts to {1}", 1024, o.Convert( 1024 ) ); 



      // let's test our HexConverter clsss      
      HexConverter h = new HexConverter();       Console.WriteLine( "{0} hex converts to {1}", 1024, h.Convert( 1024 ) );

      // we're done with these classes, set them to null so that the garbage collecter 
      // will know that we're done with them
      c = null; 
      b = null; 
      o = null; 
      h = null; 

      // wait for any key press (keeps the command window from closing on us)
      Console.ReadKey( true );
    } 
  } 
} 

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 


Video