Search code examples
cbinaryoctal

Converting binary to octal using strings


I have to convert hexadecimal numbers to octal numbers by converting hex numbers to binary first, and from binary to octal.

#include <stdio.h>
#include <string.h>
int main(){
    char binarni_brojevi[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
    char heksadekadni_broj[] = "AF1";
    int i, vrednost;
    char binarni[50];
    binarni[0] = '\0';
    for(i = 0; heksadekadni_broj[i]; i++) {
        if(isalpha(heksadekadni_broj[i]))
            vrednost = (heksadekadni_broj[i] - 'A' + 10);
        else
            vrednost = (heksadekadni_broj[i] - '0');
        strcat(binarni, binarni_brojevi[vrednost]);
    }
    // what do I do from here? How should I group by 3
    return 0;
}

Solution

  • 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.