2進数を10進数に変えるには、例えば、1001を10進数に変換する場合、1001の1に1をかけて1、次に0に2を掛けて0、次に0に4をかけて0、次に1に8を掛けて8、最後に全部足した値の9が10進数の数値になる。20から23までの1, 2, 4, 8までの重みをそれぞれの位に掛けて得られた値の合計を求めることで2進数は10進数へ変換できる。
このアルゴリズムをC++でプログラミングするには、合計をtotal、重みをweightとする関数を作る必要がある。とりあえず関数名はbdとする。
1 2 3 | int bd(int a){ int weight = 1; //重み = power of 2 (1, 2, 4, 8, 16, 32...) int total = 0; |
例えば、111を10進数に変換する場合、total=(1*1)+(1*2)+(1*4)=7になる。
これは、111%10, 11%10, 1%10に、weight*2(1, 2, 4)を掛けていく事で実現可能。
1 2 3 4 5 | while (a != 0){ total += (a%10)*weight; a /= 10; //a = a/10 (a = 111, 11, 1, 0) weight *= 2; //weight = weight*2 (weight = 1, 2, 4)} return total; |
最終的なコードは以下のようになる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include using namespace std; int bd(int a) { int weight = 1; //重み = power of 2 (1, 2, 4, 8, 16, 32...) int total = 0; while (a != 0) { total += (a % 10) * weight; a /= 10; // a = a/10 (a = 111, 11, 1, 0) weight *= 2; // weight = weight*2 (weight = 1, 2, 4) } return total; } int main() { int n; cout << "Enter a binary number:"; cin >> n; cout << "binary " << n << " is " << bd(n) << endl; return 0; } |
Pythonで2進数を10進数に変換するコードは以下のようになる。
pythonの内部コマンドを使いたくない場合のコードは以下のようになる。
Python2の方でプログラミングしたので、raw_inputになっている。
参考サイトhttps://stackoverflow.com/スポンサーリンク
スポンサーリンク