14 July 2010

Get bases for decimal nubmers

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

#define SIZE sizeof(unsigned)* CHAR_BIT
//#define DEBUG

int main(void){


char digits[]={'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
char ret[SIZE] = {0};
unsigned n, b;

printf("Enter a Positive number? " );
scanf("%u", &n);
printf("Enter Base? " );
scanf("%u", &b);

int i=0;
do{
ret[i++] = n%b;
n /=b;

}while (n>0);

#ifdef DEBUG
for (i=0; i<SIZE;i++)
printf("%i", ret[i]);
printf("\n");
#endif

// SWAP:
for (i=0; i<SIZE/2;i++){
int tmp=ret[i];
ret[i] = ret[SIZE-i-1];
ret[SIZE-i-1] = tmp;
}

for (i=0; i<SIZE;i++)
printf("%c", digits[ret[i]]);


printf("\n");
return 0;
}

Post a Comment