Decimal, hexadecimal and octal numbers in C++

This topic shows  how declare and display variables in C++ with diffrent numerical systems.

The first programm displays 255 value in hexadecimal, octal and decimal system.

using namespace std;

int main()
  short value = 255;
  cout << hex;
  cout << "hexadecimal value: " << value << endl;
  cout << oct;
  cout << "octal value: " << value << endl;
  cout << dec;
  cout << "decimal value: " << value << endl;
  return 0;

The hex function set hexadecimal numbers. If You would like to change it in programm must use dec function to come back to decimal system. The oct function set octal system. The variable may be one of integer datatype. I use in this programm short datatype.

In next programm the every variable containts value of diffrent numerical system. First is decimal, it is default system, so You may not add nothing before it value. Second is octal number, so You must add to the value 0 preffix. If You want to set hexadecimal value You need add to the value 0x or 0X preffix.

using namespace std;

int main()
  short dec_value = 255;
  short hex_value = 0xff;
  short oct_value = 0377;

  cout << "decimal 255 value is decimal " << dec_value << endl;
  cout << "hexadecimal 0xff value is decimal " << hex_value << endl;
  cout << "octal 0377 value is decimal " << oct_value << endl;

  return 0;

In C++11 it is available to use  declaration and initialization  variables in this way, without equal sign:

  short dec_value {255};
  short hex_value {0xff};
  short oct_value {0377};

2 thoughts on “Decimal, hexadecimal and octal numbers in C++

  1. Ashly

    Great post. I used to be checking continuouslly this weblog and I amm inspired!

    Extremely useful information specifically thee remaining phase 🙂 I
    handle such information a lot. I used to be seeking this particular information for a long time.
    Thanks and best of luck.


Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.