使用字符串将二进制转换为八进制

Converting binary to octal using strings

我必须先将十六进制数转换为二进制数,然后再从二进制数转换为八进制数,从而将十六进制数转换为八进制数。

#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] = '[=10=]';
    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;
}

不太清楚你要达到的目标。

您可以像这样将整型变量转换为八进制:sprintf(string, "%o", value);。如果您的数字变量作为字符串保存,则该问题仅在人类可读格式的上下文中有意义;)

此示例演示如何将十六进制字符串转换为八进制字符串。我不知道你为什么需要一组 16 个二进制字符串模式。

#include <stdio.h>

int main(void){
    char heksadekadni_broj[] = "AF1";
    char octal[50];
    int vrednost;

    sscanf(heksadekadni_broj, "%x", &vrednost);     // read in the hex value
    sprintf(octal, "%o", vrednost);                 // put out as octal

    printf ("Heks: %s, Octal: %s\n", heksadekadni_broj, octal);
    return 0;
}

程序输出:

Heks: AF1, Octal: 5361

要将字符按 3 分组,请先数一数有多少个:

int num_of_binary_digits = strlen(binarni);

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

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

计算八进制数的个数,除以3with rounding up:

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;
    for (int bd = 0; bd < bits_in_group; ++bd)
    {
        ...
    }
}

在内部循环中,您必须将一串字符(如“11”或“110”)转换为数字(如 3 或 6)。这应该很容易。

要将二进制字符串转换为八进制字符串,如果在[0 UINTMAX_MAX]范围内,使用库函数strtoumax()snprintf()

#include <errno.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>

// return 0 on success, else return 1
int binary_to_octal_string(char *ostr, size_t osize, const char *bstr) {
  char *endptr;
  errno = 0;
  uintmax_t y = strtoumax(bstr, &endptr, 2);
  // If trouble with conversion (overflow, empty string, non-'0' or '1' found)
  if (errno || bstr == endptr || *endptr) return 1;

  int n = snprintf(ostr, osize, "%" PRIoMAX, y);
  // If destination buffer too small or unlikely encoding error ...
  if (n >= osize || n < 0) return 1;

  return 0;
}