For this exercise, you will write a program to convert numbers to different base
ID: 3778263 • Letter: F
Question
For this exercise, you will write a program to convert numbers to different bases. For example:
FF16 = 25510 = 3778 = 111111112 = C321 = 7336
Your program will prompt the user to enter a number and the base of the number. It will then ask what base to convert the number to. Your program will handle bases 2-36.
Your program should include the following features:
- If the user enters a base outside the range, display an error message and make the user reenter the base.
- If the number doesn’t match the base the user typed in (i.e., the character A is invalid for a base 10 numbers), display an error message and have the user reenter all of the information again.
- The number displayed to the user should be displayed in uppercase.
- Be sure your output is self-documenting. For example: FF(base 16) = 255(base 10).
Hints:
- The maximum digit that can be in a number is one less than its base. For example, 7 is the maximum digit in a base 8 number, and 1 is the maximum digit in a base 2 number.
- Convert all numbers to base 10 first and then convert them to the desired base.
- Since the number is entered into a character array, each digit is a character. You must convert this ASCII value to the appropriate value for that base. For example, A is value 10, B is value 11; to calculate these values, use the ASCII value for the alphabetic character and subtract 55. This works because A is ASCII value 65, B is ASCII value 66. If the character in the array happens to be a digit (i.e., numeral), use the same philosophy but subtract 48.
If you are unsure how to change bases, please review Chapter 1.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
char string[1024];
int length;
printf("ASCII Input: ");
gets(string);
printf(" ");
printf(" ");
printf("Decimal Ouput:");
for(length = 0; length < strlen(string); length++)
{
printf("%d ", string[length]);
}
printf(" ");
printf("Hexadecimal Output: ");
for(length = 0; length < strlen(string); length++)
{
printf("%x ", string[length]);
}
printf(" ");
printf("Octal Output:");
for(length = 0; length < strlen(string); length++)
{
printf("%o ", string[length]);
}
printf(" ");
printf(" ");
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.