是否有任何实用程序或库提供简单的函数来转换十六进制/二进制格式之间的字符串?我一直在搜索SO,目前正在使用查找表方法.顺便说一下,由于它可能是一个长字符串,我不会考虑将字符串转换为整数并处理格式转换,因为长字符串可能大于MAX_INT(或其他整数数据类型).
例如:
0xA1 => 10100001
11110001 => 0xF1
Run Code Online (Sandbox Code Playgroud)
PS:我的项目使用Boost 1.44,有点过时了.因此,如果该实用程序来自Boost,希望它可以在1.44中使用.
Sil*_*lex 21
您可以使用C++ 03中的十六进制和二进制的组合std::stringstream,std::hex并std::bitset进行转换.
这是一个例子:
#include <iostream>
#include <sstream>
#include <bitset>
#include <string>
using namespace std;
int main()
{
string s = "0xA";
stringstream ss;
ss << hex << s;
unsigned n;
ss >> n;
bitset<32> b(n);
// outputs "00000000000000000000000000001010"
cout << b.to_string() << endl;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
关于精炼的问题,这里是关于在十六进制字符串和二进制字符串之间进行转换的代码示例(您可以使用十六进制字符<>位部分的辅助函数进行重构,并使用映射或开关等).
const char* hex_char_to_bin(char c)
{
// TODO handle default / error
switch(toupper(c))
{
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'B': return "1011";
case 'C': return "1100";
case 'D': return "1101";
case 'E': return "1110";
case 'F': return "1111";
}
}
std::string hex_str_to_bin_str(const std::string& hex)
{
// TODO use a loop from <algorithm> or smth
std::string bin;
for(unsigned i = 0; i != hex.length(); ++i)
bin += hex_char_to_bin(hex[i]);
return bin;
}
Run Code Online (Sandbox Code Playgroud)
以下代码包含两个完全按照您的要求执行的功能.这是基于Silex的答案,但有一些额外的字符串操作来匹配您在问题中给出的示例输出.
#include <iostream>
#include <sstream>
#include <bitset>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
const unsigned g_unMaxBits = 32;
string Hex2Bin(const string& s)
{
stringstream ss;
ss << hex << s;
unsigned n;
ss >> n;
bitset<g_unMaxBits> b(n);
unsigned x = 0;
if (boost::starts_with(s, "0x") || boost::starts_with(s, "0X")) x = 2;
return b.to_string().substr(32 - 4*(s.length()-x));
}
string Bin2Hex(const string& s)
{
bitset<g_unMaxBits> bs(s);
unsigned n = bs.to_ulong();
stringstream ss;
ss << hex << n;
return "0x" + boost::to_upper_copy(ss.str());
}
int main()
{
cout << "0xA1 => " << Hex2Bin("0xA1") << endl;
cout << "B3 => " << Hex2Bin("B3") << endl;
cout << "11110001 => " << Bin2Hex("11110001") << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)