十六进制到八进制转换程序,不使用十进制或二进制

For*_*ner 4 c hex octal

今天我只是在玩一个从一个基地到另一个基地的基本转换.我调整了一些代码,用于从十六进制转换为八进制,我注意到它主要使用中间转换为十进制或二进制,然后返回到八进制.是否可以编写我自己的函数将十六进制字符串转换为八进制字符串而不使用任何中间转换.我也不想使用printf像%x或的内置选项%o.感谢您的投入.

izo*_*ica 5

当然有可能.数字是一个数字,无论它处于什么数字系统.唯一的问题是人们习惯于小数,这就是为什么他们更好地理解它.您可以从任何基地转换为任何其他基地.

编辑:有关如何执行转换的更多信息.

首先请注意,3个十六进制数字正好映射到4个八进制数字.因此,如果有十六进制数字,您可以轻松找到八进制数字的数量:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int get_val(char hex_digit) {
  if (hex_digit >= '0' && hex_digit <= '9') {
    return hex_digit - '0';
  } else {
    return hex_digit - 'A' + 10;
  }
}
void convert_to_oct(const char* hex, char** res) {
  int hex_len = strlen(hex);
  int oct_len = (hex_len/3) * 4;
  int i;

  // One hex digit left that is 4 bits or 2 oct digits.
  if (hex_len%3 == 1) {
    oct_len += 2;
  } else if (hex_len%3 == 2) { // 2 hex digits map to 3 oct digits
    oct_len += 3;
  }

  (*res) = malloc((oct_len+1) * sizeof(char));
  (*res)[oct_len] = 0; // don't forget the terminating char.

  int oct_index = oct_len - 1; // position we are changing in the oct representation.
  for (i = hex_len - 1; i - 3 >= 0; i -= 3) {
    (*res)[oct_index] = get_val(hex[i]) % 8 + '0';
    (*res)[oct_index - 1] = (get_val(hex[i])/8+ (get_val(hex[i-1])%4) * 2) + '0';
    (*res)[oct_index - 2] = get_val(hex[i-1])/4 + (get_val(hex[i-2])%2)*4 + '0';
    (*res)[oct_index - 3] = get_val(hex[i-2])/2 + '0'; 
    oct_index -= 4;
  }

  // if hex_len is not divisible by 4 we have to take care of the extra digits:
  if (hex_len%3 == 1) {
     (*res)[oct_index] = get_val(hex[0])%8 + '0';
     (*res)[oct_index - 1] = get_val(hex[0])/8 + '0';
  } else if (hex_len%3 == 2) {
     (*res)[oct_index] = get_val(hex[1])%8 + '0';
     (*res)[oct_index - 1] = get_val(hex[1])/8 + (get_val(hex[0])%4)*4 + '0';
     (*res)[oct_index - 2] = get_val(hex[0])/4 + '0';
  }
}
Run Code Online (Sandbox Code Playgroud)

这里也是关于ideone的示例,以便您可以使用它:示例.