二进制转换为八进制字符串使用 [英] Converting binary to octal using strings

查看:335
本文介绍了二进制转换为八进制字符串使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过转换十六进制数为二进制先十六进制数八进制数转换,并且从二元到八进制。

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
诠释主(){
    炭binarni_brojevi [16] [5] = {0000,0001,0010,0011,0100,0101,0110,0111,1000,1001, 1010,1011,1100,1101,1110,1111};
    烧焦heksadekadni_broj [] =AF1;
    INT I,vrednost;
    焦炭binarni [50];
    binarni [0] ='\\ 0';
    对于(i = 0; heksadekadni_broj [I];我++){
        如果(因而isalpha(heksadekadni_broj [I]))
            vrednost =(heksadekadni_broj [I] - 'A'+ 10);
        其他
            vrednost =(heksadekadni_broj [I] - '0');
        strcat的(binarni,binarni_brojevi [vrednost]);
    }
    //我该怎么在这里做什么?我应该怎么组由3
    返回0;
}


解决方案

要字符组3,先算有多少:

  INT num_of_binary_digits = strlen的(binarni);

这可能不会被3整除例如:

 二进制字符串:00001111
分为3组:00 | 001 | 111

要与四舍五入算八进制数字3 数,除以:

  INT num_of_octal_digits =(num_of_binary_digits + 2)/ 3;

要确定有多少个二进制数字有在第一组中,使用一些基本的算术(我把它出简洁)。

然后做嵌套循环:

 的for(int OD = 0; OD< num_of_octal_digits ++ OD)
{
    INT bits_in_group =(OD == 0)? digits_in_first_group:3;
    对于(INT BD = 0; BD< bits_in_group ++ BD)
    {
        ...
    }
}

内环内,您将不得不像11或110字符的字符串转换为数字像3或6。这应该很容易。

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;
}

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.

这篇关于二进制转换为八进制字符串使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆