How to convert a Decimal to Octal using C#?


To get the octal equivalent, use a while loop for the decimal value and store the remainder in the array set for octal. Here we have set the remainder by mod 8 in the array.

Then divide the number by 8 −

while (dec != 0) {
   oct[i] = dec % 8;
   dec = dec / 8;
   i++;
}

Let us see the complete code.

Here, our decimal number is 18 −

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {

         int []oct = new int[30];

         // decimal
         int dec = 18;

         int i = 0;
         while (dec != 0){
            oct[i] = dec % 8;
            dec = dec / 8;
            i++;
         }

         for (int j = i - 1; j >= 0; j--)
         Console.Write(oct[j]);

         Console.ReadKey();
      }
   }
}

Updated on: 21-Jun-2020

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements