convert a number from base 10 to base 8 in csharp

To convert a number from base 10 to base 8 in C#, you can use the following algorithm:

  1. First, declare two variables, "number" and "result".
  2. Set "number" equal to the decimal number you wish to convert.
  3. Loop through the following steps while "number" is greater than 0:
    • Calculate the remainder of "number" when divided by 8.
    • Add the remainder to the beginning of "result".
    • Divide "number" by 8 and truncate any decimal values.
  4. The value of "result" will be the base 8 equivalent of the original decimal number.

Here's the C# code for this algorithm:

main.cs
int number = 123;
string result = "";

while (number > 0)
{
    int remainder = number % 8;
    result = remainder.ToString() + result;
    number /= 8;
}

Console.WriteLine(result); // outputs "173"
200 chars
12 lines

In this example, we're converting the decimal number 123 to its base 8 equivalent, which is 173. The final result is stored in the string variable "result".

gistlibby LogSnag