You can use a combination of std::stringstream
, std::hex
and std::bitset
to convert between hex and binary in C++03.
Here's an example:
#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;
}
EDIT:
About the refined question, here's a code example about converting between hex strings and binary strings (you can refactor with a helper function for the hex char<>bits part, and use a map or a switch instead, etc).
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…