Write a C program, convert2tenandhex.c that takes one command line parameter. Th
ID: 3883545 • Letter: W
Question
Write a C program, convert2tenandhex.c that takes one command line parameter. The parameter is an integer either in decimal or hexadecimal. If it is in hexadecimal, it starts with a leading 0x. The program outputs exactly 2 lines. The first line contains only your name. If the program has exactly one command line parameters, the second line contains two tokens separated by a single blank. The first token is the value of the parameter in decimal and the second token is the value of the parameter in hexadecimal (without the leading 0x). If the number of command line parameters is not correct, the second line is an appropriate error message. Run the program three times, once with no command line parameters, once with your student ID and once with its hexadecimal equivalent (with he leading 0x). Put both the input and output for the three runs in a file called assign 1-3.out. Make sure each run is clearly labeled. You may assume that the value specified on the command line will fit in an int.Explanation / Answer
#include <stdio.h>
#include <errno.h> // for errno
#include <limits.h> // for INT_MAX
#include <stdlib.h> // for strtol
#include <math.h>
#include <string.h>
void hex2dec(char hexadecimal[30])
{
int decimalNumber = 0;
char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int i, j, power=0, digit;
/* Converting hexadecimal number to decimal number */
for(i=strlen(hexadecimal)-1; i >= 2; i--) {
/*search currect character in hexDigits array */
for(j=0; j<16; j++){
if(hexadecimal[i] == hexDigits[j]){
decimalNumber += j*pow(16, power);
}
}
power++;
}
printf("%d", decimalNumber);
}
void dec2Hex(int decimalnum)
{
long quotient, remainder;
int i, j = 0;
char hexadecimalnum[100];
quotient = decimalnum;
while (quotient != 0)
{
remainder = quotient % 16;
if (remainder < 10)
hexadecimalnum[j++] = 48 + remainder;
else
hexadecimalnum[j++] = 55 + remainder;
quotient = quotient / 16;
}
for (i = j-1; i >= 0; i--)
printf("%c", hexadecimalnum[i]);
}
int main(int argc, char *argv[]) {
if (argc != 2)
{
printf("Error: Enter only one parameter ");
return 1;
}
if (argv[1][0] == '0' && argv[1][1] == 'x')
{
hex2dec(argv[1]);
printf(" %s ", argv[1]);
}
else {
int num = atoi(argv[1]);
printf("%d ", num);
dec2Hex(num);
printf(" ");
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.