Search code examples
c++hexuintiomanip

1 byte integer doesn't convert i/o formats


I wrote the code below which inputs a number in hex format and outputs it in decimal form:-

#include<iostream>
#include<iomanip>
#include<stdint.h>

using namespace std;

int main()
{
  uint8_t c;
  cin>>hex>>c;
  cout<<dec<<c;
  //cout<<sizeof(c);
  return 0;
}

But when I input c(hex for 12), the output was again c(and not 12). Can somebody explain?


Solution

  • This is because uint8_t is usually a typedef for unsigned char. So it's actually reading 'c' as ASCII 0x63.

    Use int instead.

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
        int c;
        cin>>hex>>c;
        cout<<dec<<c<<'\n';
        return 0;
    }
    

    Program output:

    $ g++ test.cpp
    $ ./a.out
    c
    12