Created
October 8, 2013 01:38
-
-
Save santosh/6878058 to your computer and use it in GitHub Desktop.
Program to convert a base 10 integer to base 2, 8 and 16.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* File: 7.7.c | |
* Author: Santosh Kumar <[email protected]> | |
* Date created: Tue 08 Oct 2013 06:33:28 IST | |
* Description: Program to convert a positive integer to another base | |
* Taken from 'Programming in C' book. | |
*/ | |
#include <stdio.h> | |
int main(int argc, char *argv[]) { | |
const char baseDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; | |
int convertedNumber[64]; | |
long int numberToConvert; | |
int nextDigit, base, index = 0; | |
// get the number and the base | |
printf("Number to be converted? "); | |
scanf("%ld", &numberToConvert); | |
printf("Base? "); | |
scanf("%i", &base); | |
// convert to the indicated base | |
do { | |
convertedNumber[index] = numberToConvert % base; | |
++index; | |
numberToConvert = numberToConvert / base; | |
} while(numberToConvert != 0); | |
// display the result in reverse order | |
printf("Converted number = "); | |
for (--index; index >= 0; --index) { | |
nextDigit = convertedNumber[index] ; | |
printf("%c", baseDigits[nextDigit]); | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment