How to convert a Decimal to Octal using C#?

CsharpProgrammingServer Side Programming

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();
      }
   }
}
raja
Published on 13-Aug-2018 17:06:17
Advertisements