DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C# (http://www.daniweb.com/forums/forum61.html)
-   -   decimal to hexadecimal (http://www.daniweb.com/forums/thread164086.html)

Egypt Pharaoh Dec 25th, 2008 7:31 am
decimal to hexadecimal
 
I want the code of program that convert from "decimal to hexadecimal "and from "hexadecimal to decimal " in console applicathion

Egypt Pharaoh Dec 25th, 2008 7:35 am
Re: decimal to hexadecimal
 
there is the code I have but I don't know if it was right or wrong from "decimal to hexadecimal"
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
           
            Console.WriteLine("Enter the number that you want to convert to Hexadecimal ");
            int n = int.Parse(Console.ReadLine());

            Console.Write("{0}=",n);
            ToHexadecimal(n);
            Console.ReadKey();

        }
        static void ToHexadecimal(int n)
        {
            if (n == 0)
                return;
            else
            {
                int r = n % 16;
                n =n/ 16;
                ToHexadecimal(n);
             
               
                switch (r)
                {
                    case 10:
                        Console.Write("A");
                        break;
                    case 11:
                        Console.Write("B");
                        break;
                    case 12:
                        Console.Write("C");
                        break;
                    case 13:
                        Console.Write("D");
                        break;
                    case 14:
                        Console.Write("E");
                        break;
                    case 15:
                        Console.Write("F");
                        break;
                    default:
                        Console.Write(r);
                        break;
                   
                }

            }
        }

    }
}

ddanbe Dec 25th, 2008 8:24 am
Re: decimal to hexadecimal
 
Off course you can always save you the trouble of doing it yourself and use format specifiers like this:
int value = 32767;
Console.WriteLine("{0,10:G}: {0,10 : X}", value);
Which will output:

32767: 7FFF

hieuuk Dec 28th, 2008 8:19 pm
Re: decimal to hexadecimal
 
this also does the trick to convert from hex -> number:
int.Parse(Hex, System.Globalization.NumberStyles.HexNumber);
for bigger value
long.Parse(Hex, System.Globalization.NumberStyles.HexNumber);
other way round
string hex = Value.ToString("x");


All times are GMT -4. The time now is 4:19 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC