How can I handle hex input and convert to decimal?

Posted on 2003-03-22
Medium Priority
Last Modified: 2011-08-18

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);
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2

Accepted Solution

gj62 earned 300 total points
ID: 8187739
%x in your scanf will treat the incoming value as hex, and assign it to your int...

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

Author Comment

ID: 8187887
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?


Expert Comment

ID: 8188887
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question