C++ 03では、std::stringstream
,std::hex
およびstd::bitset
の組み合わせを使用して、16進数と2進数の間の変換を行うことができます。ここで
は例です:
#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:洗練された質問について
が、ここでは進文字列とバイナリ文字列の間の変換についてのコード例です(あなたが進文字のためのヘルパー関数をリファクタリングすることができます<>ビット部分を使用し、代わりに地図やスイッチなどを使用します)。
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;
}
どのような「16進/ 2進形式」ですか?いくつかの例を与えるためにケア? –