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
publicstaticstringBase2ToBase8(string base2){
// Pad the base 2 number with leading zeroes if necessarywhile (base2.Length % 3 != 0)
{
base2 = "0" + base2;
}
// Divide the base 2 number into groups of 3 digits eachstring[] groups = newstring[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 8int[] octalValues = newint[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 resultreturnstring.Join("", octalValues);
}
718 chars
26 lines
To use this method, simply pass in the base 2 number as a string: