基本表現
名前 | 形 |
---|---|
バイナリ | 0b +コンテンツ/ 0B +コンテンツ |
オクタル | 0+コンテンツ |
10進数 | コンテンツ |
16進数 | 0x + content / 0x + content |
テスト手順は次のとおりです。
#include <iostream>
using namespace std;
int main()
{
int a = 20;
int b = 024;
int c = 0x14;
int d = 0X14;
int e = 0b10100;
int f = 0B10100;
int b2 = 0024;
int c2 = 0x014;
// int c3 = 00x14; //This is an error.
int e2 = 0b010100;
cout << a << " " << b << " " << c << " " << d << " " << e <<
" " << f << " " << b2 << " " << c2 << " " << e2 << endl;
return 0;
}
結果:
20 20 20 20 20 20 20 20 20
ベース変換
以下は、ヘッダーファイルBinary.hの2進数から10進数への変換関数を定義しています。1
. binary_to_decimal():2進数→10進数
2. decimal_to_binary():10進数→バイナリ
#ifndef BINARY_H
#define BINARY_H
#include <cmath>
int binary_to_decimal(unsigned long bin1)
{
unsigned long dec1 = 0;
unsigned long tem1 = bin1;
unsigned i = 0;
while (tem1 != 0)
{
dec1 += pow(2, i++) * (tem1 % 10);
tem1 /= 10;
}
return(dec1);
}
int decimal_to_binary(unsigned long dec2)
{
unsigned long bin2 = 0;
unsigned long tem2 = dec2;
unsigned j = 0;
while (tem2 != 0)
{
bin2 += pow(10, j++) * (tem2 % 2);
tem2 /= 2;
}
return(bin2);
}
#endif // !BINARY_H
使用例は、[C ++ Primer(5th Edition)演習]演習プログラム-第4章演習セクション4.8にあります(つまり、演習4.25-27)。
また、パワーが^ !!!ではないことにも注意してください。この記号は英語バージョンP154で説明されています。
もちろん、類推によって他の16進変換プログラムを書くこともできます。
こちらもご覧ください
テディヴァンジェリーのナビゲーションページ
[C ++ Primer(5th Edition)Exercise]演習プログラム-第2章(第2章)