[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 183
  • Last Modified:

How can I handle hex input and convert to decimal?

Hi,

I'm writing a program which will prompt the user an offset to be used to dump the contents of a file to hex. The offset is to be entered in hex. For example if they enter f I want to convert it to 15. I'm an old goat trying to learn, so be gentle. Thanks. The following is what I've been trying with no luck.

  unsigned int n;
  char line[10];
     
  printf("enter a hex\n");
 
  fgets(line, 10, stdin);      
  scanf(line,"%d", &n);
 
0
old_goat_trying_to_learn
Asked:
old_goat_trying_to_learn
  • 2
1 Solution
 
gj62Commented:
%x in your scanf will treat the incoming value as hex, and assign it to your int...

scanf(line,"%x", &n);
0
 
old_goat_trying_to_learnAuthor Commented:
Thanks gj62,

I had tried that before(sorry for not mentioning it), but it didn't work. It worked once I used sscanf rather than scanf. If I may ask...why?

Thanks
0
 
gj62Commented:
Sorry, should have seen that to begin with...

scanf reads from stdin (the keyboard, in most cases)

sscanf reads from a string.

So, when you said:

scanf(line,"%x", &n);

it was actually looking in line for the format string...

in

sscanf(line,"%x", &n);

it knew that line was the input buffer.

Functions that have a variable number of args can't do alot of checking, and that's a common bug to have happen...
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now