从十六进制转换为二进制的C++代码如下:
#include<iostream>
#include<string>
#include <bitset>
using namespace std;
string hexToBinary(string hex) {
string binary = "";
for (char c : hex) {
switch (c) {
case '0': binary += "0000"; break;
case '1': binary += "0001"; break;
case '2': binary += "0010"; break;
case '3': binary += "0011"; break;
case '4': binary += "0100"; break;
case '5': binary += "0101"; break;
case '6': binary += "0110"; break;
case '7': binary += "0111"; break;
case '8': binary += "1000"; break;
case '9': binary += "1001"; break;
case 'A': binary += "1010"; break;
case 'B': binary += "1011"; break;
case 'C': binary += "1100"; break;
case 'D': binary += "1101"; break;
case 'E': binary += "1110"; break;
case 'F': binary += "1111"; break;
default: break;
}
}
return binary;
}
int main() {
string hex;
cout << "请输入十六进制数:";
cin >> hex;
string binary = hexToBinary(hex);
cout << "转换为二进制后的结果为:"<< binary<< endl;
return 0;
}
这段代码可以将输入的十六进制数转换为二进制数。其中,hexToBinary
函数将十六进制字符串转换为二进制字符串,main
函数则负责接收用户输入并调用hexToBinary
函数进行转换。
领取专属 10元无门槛券
手把手带您无忧上云