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

  • Thread starter Thread starter Guest
  • Start date Start date
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!
 
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;
 
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.)
 
Back
Top