C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Read/write integer value using Decimal, Octal and Hexadecimal Base formats in C++

Traditionally, cout reads/writes values in Decimal format. To read/write values in other Base formats like 'Octal Base format', 'Hexadecimal Base format', there are some C++ manipulators [Read: other C++ Manipulator]

dec - for Decimal Base format
oct - for Octal Base format
hex - for Hexadecimal Base format

Example:

In this example, we will print (write) the value of a variable named var (the value of var is 100 in Decimal Base format) in Octal Base format, Decimal Base format and Hexadecimal Base format.

#include <iostream>
using namespace std;

int main()
{
	int var=100;
	cout<<"Decimal Base format: "		<<dec<<var<<endl;
	cout<<"Octal Base format: " 		<<oct<<var<<endl;
	cout<<"Hexadecimal Base format: "	<<hex<<var<<endl;
	
	return 0;
}

Output

Decimal Base format: 100
Octal Base format: 144
Hexadecimal Base format: 64

Note: there is no need to use dec Manipulator to print in Decimal Base format, because cout prints the value in Decimal Base format.

Example:

In this example, we will print the value of three variables var1, var2 and var3, these are the integer variables which are initializing with values in Decimal, Octal and Hexadecimal Base format respectively.

#include <iostream>
using namespace std;

int main()
{
	int var1 = 100; 	//Decimal Base format
	int var2 = 0144; 	//Octal Base format
	int var3 = 0x64;	//Hexadecimal Base format
	
	cout<<"var1: "<<var1<<endl;
	cout<<"var2: "<<var2<<endl;
	cout<<"var3: "<<var3<<endl;
	
	return 0;
}

Output

var1: 100
var2: 100
var3: 100

var1, var2 and var3 was initialized with Decimal, Octal and Hexadecimal formats respectively, cout prints all values in Decimal formats, thus it clears that cout prints in only Decimal formats if we do not use any manipulator.







COMMENTS