0

hi,

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

your help is greatly appreciated.

Beulah

3
Contributors
4
Replies
8
Views
11 Years
Discussion Span
Last Post by beuls
0
#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?

0

>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. ;)

0

>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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.