Get a value and print its corresponding hexadecimal number.
Understanding Number Bases
Computers can display the same number in different bases (number systems). C++ provides powerful manipulators to control how integers are displayed.
Manipulator | Base | Digits Used | Example (255) |
---|---|---|---|
std::dec |
10 (Decimal) | 0-9 | 255 |
std::hex |
16 (Hexadecimal) | 0-9, a-f | ff |
std::oct |
8 (Octal) | 0-7 | 377 |
int num = 255;
cout << dec << num << endl; // 255
cout << hex << num << endl; // ff
cout << oct << num << endl; // 377
std::uppercase
→ prints hex letters A–F
in uppercasestd::nouppercase
→ prints letters a–f
(default)int num = 255;
cout << hex << num << endl; // ff
cout << uppercase << hex << num << endl; // FF
std::showbase
→ adds prefix (0x
for hex, 0
for octal)std::noshowbase
→ disables prefix (default)int num = 255;
cout << showbase << hex << num << endl; // 0xff
cout << uppercase << hex << num << endl; // 0XFF
cout << oct << num << endl; // 0377
Manipulator | Purpose | Duration |
---|---|---|
setw(n) |
Set width to n characters | Next output only |
setfill(c) |
Fill character for padding | Persistent |
int num = 255;
cout << setw(6) << setfill('0') << hex << num;
// Output: 0000ff
Negative numbers show a minus sign in hex/octal by default:
int n = -255;
cout << hex << n; // -ff
// Two's complement (unsigned style):
cout << hex << static_cast<unsigned int>(n);
// Output: ffffff01
int num;
cin >> num;
// Decimal
cout << "Decimal: " << dec << num << '\n';
// Hex lowercase
cout << "Hex: " << hex << nouppercase << num << '\n';
// Hex uppercase with 0x prefix
cout << "Hex (0X): " << showbase << uppercase << num << '\n';
// Octal with prefix
cout << "Octal: " << showbase << oct << num << '\n';
// Padded hex
cout << setw(6) << setfill('0') << hex << num;
// Reset to default
cout << dec << noshowbase << nouppercase;
showbase
+ uppercase
= 0XFF
(not just FF
)setw()
only affects next value, setfill()
stickshexfloat
is used)Goal | Code |
---|---|
Lowercase hex | hex << nouppercase |
Uppercase hex | hex << uppercase |
Hex with 0x | showbase << hex |
Padded hex | setw(n) << setfill('0') << hex |
Reset to decimal | dec << noshowbase |
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long long a;
cin >> a;
// hex: Displays number in hexadecimal (base 16)
// Uses digits 0-9 and letters a-f
// Example: 100 → 64, 255 → ff
cout << hex << a;
return 0;
}