Convert a decimal number to a number in a any base - C Function

C examples for Function:Utility Function

Description

Convert a decimal number to a number in a any base

Demo Code

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

void to_base_n(int integer, int base);

int main(void) {
  int integer, base;

  printf("Enter an integer in base 10 and a base to convert to: ");

  while (scanf("%d %d", &integer, &base) == 2){
    to_base_n(integer, base);//from w  w w  . ja v a2  s .c  o  m
    putchar('\n');
    printf("Enter an integer in base 10 and a base to convert to: ");
  }
  return 0;
}

void to_base_n(int integer, int base){
  if (base < 2 || 10 < base){
    printf("Error: base must be between 2 and 10.");
    return;
  }

  // stop recursion
  if (integer == 0) return;

  // handle negative integers
  if (integer < 0){
    putchar('-');
    integer = abs(integer);
  }

  to_base_n(integer / base, base);
  printf("%d", integer % base);
  return;
}

Related Tutorials