convert a number from base 2 to base 8 in csharp

Here's a C# method that takes a base 2 number as a string and returns its equivalent in base 8 as a string:

main.cs
public static string Base2ToBase8(string base2)
{
    // Pad the base 2 number with leading zeroes if necessary
    while (base2.Length % 3 != 0)
    {
        base2 = "0" + base2;
    }

    // Divide the base 2 number into groups of 3 digits each
    string[] groups = new string[base2.Length / 3];
    for (int i = 0; i < groups.Length; i++)
    {
        groups[i] = base2.Substring(i * 3, 3);
    }

    // Convert each group to its equivalent in base 8
    int[] octalValues = new int[groups.Length];
    for (int i = 0; i < groups.Length; i++)
    {
        octalValues[i] = Convert.ToInt32(groups[i], 2);
    }

    // Combine the base 8 values and return the result
    return string.Join("", octalValues);
}
718 chars
26 lines

To use this method, simply pass in the base 2 number as a string:

main.cs
string base2Number = "101011110";
string base8Number = Base2ToBase8(base2Number);
Console.WriteLine(base8Number); // Output: 277
129 chars
4 lines

gistlibby LogSnag