Question

C program help 4. Write a function called scan_hex. Here is its prototype: void scan_hex(int *xptr);...

C program help

4. Write a function called scan_hex. Here is its prototype:

void scan_hex(int *xptr);

Here is an example of its use, in conjunction with print_decimal. Assume that the user will type a non-negative hex number as input. Also, assume that the “digits” a-f are in lower case. Let’s say the user types 1b

int x;

scan_hex(&x);

print_decimal(x);

MODIFY THIS CODE

// function inputs a non-negative integer and stores it into *xptr.

// The format of the input is a base 16.

void scan_hex(int *xptr) {

     char buffer[256];

     char newline;

     *xptr = 0;

     scanf("%s%c", buffer, &newline); // get rid of the \n after the input

   

     // you do the rest

}   

The above code should print 27

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>

void scan_hex(int *xptr)

{

char buffer[256];

char newline;

int i,j,k,sixteen=1;

*xptr = 0;

scanf("%s%c", buffer, &newline);

for(i=0;buffer[i]!='\0';i++);

for(j=i-1;j>=0;j--)

{

if(buffer[j]>='a' && buffer[j]<='f')

{

k = buffer[j] - 87;

// to covert a=10,b=11,c=12,d=13,e=15,f=15

// printf("%d\n",buffer[j]-87);

}

else

{

k = buffer[j] - 48;

//to covert char (1-9) to int(1-9)

// printf("%d\n",buffer[j]-48);

}

//this is to convert in base 16

//if a number is of the form a4,a3,a2,a1 then *xptr = a1*(16)^0 + a2*(16)^1 + a3*(16)^2 + a4*(16)^3

*xptr = *xptr + k * sixteen;

sixteen*=16;

}

}

void print_decimal(int x)

{

printf("%d\n",x);

}

int main()

{

int x;

scan_hex(&x);

print_decimal(x);

}

Add a comment
Know the answer?
Add Answer to:
C program help 4. Write a function called scan_hex. Here is its prototype: void scan_hex(int *xptr);...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT