3. Interactive Integer <-> Hex String Manipulation Rewrite showxbits.c so
ID: 3591709 • Letter: 3
Question
3. Interactive Integer <-> Hex String Manipulation
Rewrite showxbits.c so that it reads integers one at a time from stdin using the library function scanf (the
equivalent to printf that does input -- look this up in K&R pg.157).
For each integer it reads it should write the input decimal, converted hexadecimal, and the reconverted
decimal representations. The hexadecimal output strings requested by showxbits are to be calculated by
calling itox(). To generate the reconverted decimal, you can call xtoi(). Use printf with the %x format
for integers input, %s format for hex strings you've created.
Use the value returned by scanf to end showxbits execution when it scans a non-integer (or EOF). When
scanf is properly converting a single value under its conversion %d, it should return 1 (the number of
tokens converted). See pg 245, fscanf, end of the first paragraph. The code you need to write in
showxbits could look like this:
while (scanf("%d", &n) = = 1) {
itox( hexstring, n);
m = xtoi( hexstring);
printf("%12d %s %12d ", n, hexstring, m);
}
Note: showxbits program should *not* prompt the user for input. "No prompt" is a UNIX convention
for reading files from stdin. There's a good reason for the convention. It allows you run showxbits easily
and cleanly either by typing in the input data or using input redirection. Create a typescript to show your
results. Leave your typescript file in your hw3 directory. You do not need to print it.
Explanation / Answer
Please find the C program below:
#include <stdio.h>
#include <string.h>
void itox (char *hexstring,int n)
{
int i = 0;
char t;
while(n!=0)
{
int temp = 0;
temp = n % 16;
if(temp < 10)
{
hexstring[i] = temp + 48;
i++;
}
else
{
hexstring[i] = temp + 55;
i++;
}
n = n/16;
}
// Reverse the hexadecimal array
for(int x=0, y=i-1; x<=y; x++, y--)
{
t=hexstring[x];
hexstring[x]=hexstring[y];
hexstring[y]=t;
}
hexstring[i]='';
}
int xtoi(char *hexstring)
{
int len = strlen(hexstring);
int base = 1;
int decimal = 0;
// We need to extract the characters as digits in reverse order
for (int i=len-1; i>=0; i--)
{
if (hexstring[i]>='0' && hexstring[i]<='9')
{
decimal += (hexstring[i] - 48)*base;
base = base * 16;
}
else if (hexstring[i]>='A' && hexstring[i]<='F')
{
decimal += (hexstring[i] - 55)*base;
base = base*16;
}
}
return decimal;
}
int main()
{
char hexstring[100];
int n,m;
while (scanf("%d", &n) == 1) {
itox (hexstring, n);
m = xtoi(hexstring);
printf("%12d %s %12d ", n, hexstring, m);
}
return 0;
}
Output:
$gcc -o main *.c
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.