C++如何将十六进制字符串转换为二进制字符串
作者:花好约猿上王者
这篇文章主要介绍了C++如何将十六进制字符串转换为二进制字符串问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
十六进制字符串转换为二进制字符串
一种简单的方法将十六进制字符串转为二进制字符串,不限制十六进制的字节数。
传入的十六进制字符串需要转换为大写!(%X, toupper())。
string GetBinaryStringFromHexString (string strHex)
string sReturn = "";
unsigned int len = strHex.length();
for (unsigned int i = 0; i<len; i++)
switch ( strHex[i])
case '0': sReturn.append ("0000"); break;
case '1': sReturn.append ("0001"); break;
case '2': sReturn.append ("0010"); break;
case '3': sReturn.append ("0011"); break;
case '4': sReturn.append ("0100"); break;
case '5': sReturn.append ("0101"); break;
case '6': sReturn.append ("0110"); break;
case '7': sReturn.append ("0111"); break;
case '8': sReturn.append ("1000"); break;
case '9': sReturn.append ("1001"); break;
case 'A': sReturn.append ("1010"); break;
case 'B': sReturn.append ("1011"); break;
case 'C': sReturn.append ("1100"); break;
case 'D': sReturn.append ("1101"); break;
case 'E': sReturn.append ("1110"); break;
case 'F': sReturn.append ("1111"); break;
return sReturn;
十六进制字符串转二进制字符串1的个数
建立十六进制字符串 字符“0-F” 对应二进制中1的个数的映射数组
代码如下:
#include<iostream>
#include<string>
using namespace std;
int main(){
string inputHex;
cin >> inputHex;
int bitOneNumber[16] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
inputHex = inputHex.substr(2);
int cnt = 0;
for(auto ch : inputHex){
if(ch >= '0' && ch <= '9')
cnt += bitOneNumber[ch - '0'];
else if(ch >= 'a' && ch <= 'f')
cnt += bitOneNumber[ch - 'a' + 10];
return -1;
cout << cnt << endl;
system("pause");
return 0;
十六进制字符串转为二进制字符串
遍历统计1的个数
#include<iostream>
#include<string>
using namespace std;
string HexStrToBinStr(string& inputHex){
string binStr;
for(auto ch : inputHex){
switch (ch)
case '0' : binStr += "0000"; break;
case '1' : binStr += "0001"; break;
case '2' : binStr += "0010"; break;
case '3' : binStr += "0011"; break;
case '4' : binStr += "0100"; break;
case '5' : binStr += "0101"; break;
case '6' : binStr += "0110"; break;
case '7' : binStr += "0111"; break;
case '8' : binStr += "1000"; break;
case '9' : binStr += "1001"; break;
case 'a' : binStr += "1010"; break;
case 'b' : binStr += "1011"; break;
case 'c' : binStr += "1100"; break;
case 'd' : binStr += "1101"; break;
case 'e' : binStr += "1110"; break;
case 'f' : binStr += "1111"; break;
default:
break;
return binStr;
int main(){
string inputHex;
cin >> inputHex;
inputHex = inputHex.substr(2);
string binStr = HexStrToBinStr(inputHex);
int cnt = 0;
for(auto ch : binStr)
if(ch == '1')
++cnt;
cout << cnt << endl;
cout << binStr << endl;
system("pause");
return 0;
二进制字符串转十进制字符串