Convert positive 10 base number to any number from base 2 to 16 - CSharp System

CSharp examples for System:Math Number

Description

Convert positive 10 base number to any number from base 2 to 16

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/* w w  w . ja  v  a2  s.  c  om*/

public class Main{
        /// <summary>
        /// Convert positive 10 base number to any number from base 2 to 16
        /// </summary>
        public static string From10ToAny(long num, int baseTo)
        {
            if (baseTo < 2 || baseTo > 16)
            {
                throw new ArgumentException("I can't work with numbers with base smaller than 2 and greater than 16!");
            }

            StringBuilder sb = new StringBuilder();

            long remainder = 0;

            while (num != 0)
            {
                remainder = num % baseTo;
                num /= baseTo;

                switch (remainder)
                {
                    case 10: sb.Append("A"); break;
                    case 11: sb.Append("B"); break;
                    case 12: sb.Append("C"); break;
                    case 13: sb.Append("D"); break;
                    case 14: sb.Append("E"); break;
                    case 15: sb.Append("F"); break;
                    default: sb.Append(remainder); break;
                }
            }

            return Reverser(sb.ToString());
        }
}

Related Tutorials