Pages

Friday, June 5, 2015

Number System Conversion in C#

Decimal To Binary 

public static void toBin(int dec)
        {          
          int  count=0;
          int[]bin=new int[100];
      
       while (dec >0)
       {     
           bin[count]=dec%2;    //store Binary value in array bin
           count++;
           dec = dec / 2;  //for moving from unit to ten's or next
       }
    for (int j = count- 1; j >= 0; j--)//for loop for printing the array elements in reverse
   
        Console.Write(bin[j]);
    }

Decimal To Octal :

        public static void toOct(int dec)
        {           
            int count = 0;
            int[] oct = new int[100];

            while (dec > 0)
            {
                oct[count] = dec % 8;    //store octal in oct array
                count++;
                dec = dec / 8;           //for moving from unit to ten's or next
            }
            for (int j = count - 1; j >= 0; j--)//for loop for printing the array elements in reverse
            {
                Console.Write(oct[j]);               
            }           
        }

Decimal To Hexadecimal :

public static void toHex(int dec)
        {
            int count = 0;
            int[] hex = new int[100];
            while (dec > 0)
            {
                hex[count] = dec % 16; //store stuff in array hex
                count++;
                dec = dec / 16;
            }
            for (int j = count - 1; j >= 0; j--)    //for loop for printing the array elements in reverse
                if (hex[j] < 10)                //if array element is less than 10 then printing the array element
                {
                    Console.Write(hex[j]);
                }
                else
                    switch (hex[j])  //if array element is greater than 10 then replace 10 with A uptill 15 which is F
                    {
                        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;
                    }
        }

No comments:

Post a Comment