hi,

how can you read a hexadecimal number in c++? is there any option with cin/

your help is greatly appreciated.

Beulah

Member Avatar for iamthwee
#include <iostream.h>


void main() {
    int n;
    while (cin >> n) {
        cout << "decimal: " << n << endl;
      
        //--- Print hex with leading zeros
        cout << "hex    : ";
        for (int i=2*sizeof(int) - 1; i>=0; i--) {
            cout << "0123456789ABCDEF"[((n >> i*4) & 0xF)];
        }
        cout << endl << endl;
    }
    
}

That's reading a int and converting it to hex. Can u figure out how to do da opposite?

>how can you read a hexadecimal number in c++? is there any option with cin/
The std::hex modifier works with input streams:

#include <iostream>

int main()
{
  int x;

  std::cin>> std::hex >> x;
  std::cout<< x <<'\n';
}

Type in 1B (or 1b), and the output will be 27, which is a correct conversion from hexadecimal input to decimal output.

>That's reading a int and converting it to hex.
That's evil. ;)

Member Avatar for iamthwee

>That's evil

I know wud u expect anything less from me?

>how can you read a hexadecimal number in c++? is there any option with cin/
The std::hex modifier works with input streams:

#include <iostream>

int main()
{
  int x;

  std::cin>> std::hex >> x;
  std::cout<< x <<'\n';
}

Type in 1B (or 1b), and the output will be 27, which is a correct conversion from hexadecimal input to decimal output.

Thank you

Beulah

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.