Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c - 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] = '';
    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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...