Results 1 to 1 of 1

Thread: Base Converter

  1. #1

    Thread Starter
    Addicted Member Vitani's Avatar
    Join Date
    Jul 2001
    Location
    England
    Posts
    134

    Base Converter

    This class will convert any number in any base to it's equivilent in any other base.

    Valid bases are 2 to 36 inclusive.

    Usage:
    Code:
    int dec = 255;
    string hex = BaseConverter.ToBase(dec.ToString(), 10, 16);
    
    // hex is equal to "FF"
    Although I've used the php tag, this code is C#, it just highlights better in php tags

    PHP Code:
        public class BaseConverter {

        public static 
    string ToBase(string numberint start_baseint target_base) {

          
    int base10 this.ToBase10(numberstart_base);
          
    string rtn this.FromBase10(base10target_base);
          return 
    rtn;

        }

        public static 
    int ToBase10(string numberint start_base) {

          if (
    start_base || start_base 36) return 0;
          if (
    start_base == 10) return Convert.ToInt32(number);

          
    char[] chrs number.ToCharArray();
          
    int m chrs.Length 1;
          
    int n start_base;
          
    int x;
          
    int rtn 0;

          foreach(
    char c in chrs) {

            if (
    char.IsNumber(c))
              
    int.Parse(c.ToString());
            else
              
    Convert.ToInt32(c) - 55;

            
    rtn += * (Convert.ToInt32(Math.Pow(nm)));

            
    m--;

          }

          return 
    rtn;
        
        }

        public static 
    string FromBase10(int numberint target_base) {

          if (
    target_base || target_base 36) return "";
          if (
    target_base == 10) return number.ToString();

          
    int n target_base;
          
    int q number;
          
    int r;
          
    string rtn "";

          while (
    >= n) {

            
    n;
            
    n;

            if (
    10)
              
    rtn r.ToString() + rtn;
            else
              
    rtn Convert.ToChar(55).ToString() + rtn;

          }

          if (
    10)
            
    rtn q.ToString() + rtn;
          else
            
    rtn Convert.ToChar(55).ToString() + rtn;

          return 
    rtn;
        
        }

      } 
    Last edited by Vitani; Dec 11th, 2003 at 12:13 PM.
    If you can dream it, you can do it - Moo Power!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width