將十六進位制數轉換為二進位制數的 C++ 程式
給定一個十六進位制數作為輸入,任務是將該十六進位制數轉換為二進位制數。
計算機中的十六進位制數以 16 為底數表示,二進位制數以 2 為底數表示,因為它只有兩個二進位制數字 0 和 1,而十六進位制數有從 0 到 15 的數字,其中 10 表示為 A,11 表示為 B,12 表示為 C,13 表示為 D,14 表示為 E,15 表示為 F。
要將十六進位制數轉換為二進位制數,每個數字都轉換為其 4 位二進位制對應值,然後將這些數字組合起來形成一個相應的二進位制數。
示例
Input-: 123B 1 will have binary equivalent of 4 digit -: 0001 2 will have binary equivalent of 4 digit -: 0010 3 will have binary equivalent of 4 digit -: 0011 B(11) will have binary equivalent of 4 digit -: 1011 Output-: 0001001000111011
演算法
Start Step 1 -> declare function to convert Hexadecimal to Binary Number void convert(string hexa) Declare variable as long int i = 0 Loop While(hexa[i]) Use Switch (hexa[i]) case '0': print "0000" break; case '1': print "0001" break; case '2': print "0010" break; case '3': print "0011" break; case '4': print "0100” break; case '5': print "0101" break; case '6': print "0110" break; case '7': print "0111" break; case '8': print "1000" break; case '9': print "1001" break; case 'A': case 'a': print "1010" break; case 'B': case 'b': print "1011" break; case 'C': case 'c': print "1100" break; case 'D': case 'd': print "1101" break; case 'E': case 'e': print "1110" break; case 'F': case 'f': print "111" break; default: print please enter valid hexadecimal digit End i++ End Step 2 -> In main() Declare string hexa = "123B" Print convert(hexa); Stop
示例
#include <bits/stdc++.h> #include<string.h> using namespace std; // convert Hexadecimal to Binary Number void convert(string hexa){ long int i = 0; while (hexa[i]){ switch (hexa[i]){ case '0': cout << "0000"; break; case '1': cout << "0001"; break; case '2': cout << "0010"; break; case '3': cout << "0011"; break; case '4': cout << "0100"; break; case '5': cout << "0101"; break; case '6': cout << "0110"; break; case '7': cout << "0111"; break; case '8': cout << "1000"; break; case '9': cout << "1001"; break; case 'A': case 'a': cout << "1010"; break; case 'B': case 'b': cout << "1011"; break; case 'C': case 'c': cout << "1100"; break; case 'D': case 'd': cout << "1101"; break; case 'E': case 'e': cout << "1110"; break; case 'F': case 'f': cout << "1111"; break; default: cout << "\please enter valid hexadecimal digit "<< hexa[i]; } i++; } } int main(){ string hexa = "123B"; cout << "\nEquivalent Binary value is : "; convert(hexa); return 0; }
輸出
Equivalent Binary value is : 0001001000111011
廣告