Anthea
Anthea

Reputation: 485

hex char to decimal and store output as char

I am writing a hex to dec conversion function. The input is a single character which is converted to hex and returned back as a char. Here is the function

char hex2dec(char inp)
{
    char out;
    cout << "inp:" << inp;

    if(inp >= '0' && inp <='9')
    {
        out = (inp - '0');
        cout << " out " << out;
    }
    else 
    {
        out = (toupper(inp) - 'A' + 10);
        cout << " out " << out;
    }

    return out;
}

When i pass '0' and 'A' to the function, the print i get is inp:0 out inp:A out i.e nothing is printed in out.

I am not able to find the issue..Can anyone help?

Upvotes: 0

Views: 904

Answers (4)

Artur
Artur

Reputation: 7267

What you are actually trying to print is ascii characters with codes [0-15] which are not printable characters ie you want to print 15 but you print "\x0f" etc

use:

cout << (int)out;

and you'll force cout to invoke method printing ints not chars - this will solve your issue.

..or more 'c++++ ish' ;-)

cout << static_cast(out);

..or this which for most looks weird:

cout << int(out);

Upvotes: 2

thokra
thokra

Reputation: 2904

Simply use std::stringstream for this purpose.

#include <iostream>
#include <sstream>

int main (int argc, char ** argv)
{
  // use hex formatting
  std::stringstream stream;
  stream << std::hex << 'A';

  // retrieve value of the hex input character
  int value;
  stream >> value;
  std::cout << value << std::endl; // prints 10

  // reset the stream
  stream.str ();
  stream.clear();

  // also works for strings
  stream << "0xABC" << std::endl;
  stream >> value;
  std::cout << value << std::endl; // prints 2748

  return 0;
}

Upvotes: 0

LS_For_CMU
LS_For_CMU

Reputation: 23

the reason why u got an 'A' from print is that out is char ,and after 'A' - 'A' + 10, out is a character whose ascii value is 10 instead of integer 10. So u will get a character whose ascii value is 10 instead of getting 'A'.After checking the ascii table, that character is null,which can explain why u get nothing in the output.

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 178324

Use int out instead of char out. cout prints char as a character not an integer. The ASCII values 0-15 are unprintable control characters.

Upvotes: 0

Related Questions