- 頭文件iostream中提供控制符:
- dec: 指示cout以10進制輸出。
- hex: 指示cout以16進制輸出。
- oct: 指示cout以8進制輸出。
但是二進制並沒有類似的控制符。需要使用bitset把要輸出的數本身,轉變成二進制形式輸出。
#include <iostream>
#include <Windows.h>
#include <bitset>
using namespace std;
int main()
{
int value = 0;
cout << "請輸入一個整數: ";
cin >> value;
cout << "二進制:" << (bitset<16>)value << endl; // 16表示bitset聲明的寬度,即有輸出的二進制位數。
cout << "八進制:0" << oct << value << endl;
cout << "十進制:" << value << endl;
cout << "十六進制:0x" << hex << value << endl;
system("pause");
return 0;
}