C ++程序将十六进制数转换为二进制
给定十六进制数作为输入,任务是将该十六进制数转换为二进制数。
计算机中的十六进制数用基数16表示,而二进制数用基数2表示,因为它只有两个二进制数字0和1,而十六进制数的数字是从0到15,其中10表示为A,11表示为B,12 C,13 D,E 14,F。
为了将十六进制数转换为二进制数,将每个数字转换为4位的二进制当量,然后将这些数字组合以形成一个对应的二进制数。
示例
Input-: 123B1 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
算法
StartStep 1 -> declare function to将十六进制转换为二进制数
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;
//将十六进制转换为二进制数
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
以上是 C ++程序将十六进制数转换为二进制 的全部内容, 来源链接: utcz.com/z/361677.html