Converting binary to octal using strings

To group characters by 3, first count how many there are:

int num_of_binary_digits = strlen(binarni);

This may not be divisible by 3. For example:

Binary string: 00001111
Subdivided into groups of 3: 00|001|111

To count the number of octal digits, divide by 3 with rounding up:

int num_of_octal_digits = (num_of_binary_digits + 2) / 3;

To determine how many binary digits there are in the first group, use some basic arithmetic (I left it out for brevity).

Then do nested loops:

for (int od = 0; od < num_of_octal_digits; ++od)
{
    int bits_in_group = (od == 0) ? digits_in_first_group : 3;
    for (int bd = 0; bd < bits_in_group; ++bd)
    {
        ...
    }
}

Inside the inner loop you will have to convert a string of characters like “11” or “110” into a number like 3 or 6. This should be easy.

Leave a Comment