How to implement 'atoi' when radix=16 and number string is negati

G

Guest

I'm learning C++ and was stuck when writing code to convert a negative
decimal number string to a hexdecimal number. For example, suppose the
function interface is defined as:

int atoi( const char*, size_t radix)

One input string is "-1234" and radix is 16.

How to get the correct hexdecimal integer? Can anyone help ? Thanks in
advance!
 
P

Peter van der Goes

Tracey said:
I'm learning C++ and was stuck when writing code to convert a negative
decimal number string to a hexdecimal number. For example, suppose the
function interface is defined as:

int atoi( const char*, size_t radix)

One input string is "-1234" and radix is 16.

How to get the correct hexdecimal integer? Can anyone help ? Thanks in
advance!

Let's start by agreeing that all integers are stored in memory the same way.
There is no decimal vs. hexadecimal in memory. If what you want is the
hexadecimal representation of -1234, you can use this:

char hexOutput[20];

int res = atoi("1234");

itoa(res,hexOutput,16);

cout << endl << hexOutput << endl;
 
N

Norman Diamond

I'm learning C++ and was stuck when writing code to convert a negative
decimal number string to a hexdecimal number. For example, suppose the
function interface is defined as:

int atoi( const char*, size_t radix)

One input string is "-1234" and radix is 16.

How to get the correct hexdecimal integer? Can anyone help ? Thanks in
advance!

Call strtol() and convert the result from long to int.

(I hope I didn't just finish doing your homework for you. I was amazed to
see two other people post wrong answers though.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top