[Webinar] Streamline your web hosting managementRegister Today

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

How can I handle hex input and convert to decimal?


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);
  • 2
1 Solution
%x in your scanf will treat the incoming value as hex, and assign it to your int...

scanf(line,"%x", &n);
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?

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...


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...

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