Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

c++ - Convert strings between hex format and binary format

Is there any utility or library provides a simple function to convert a string between hex/binary format? I've been searching on SO and currently using look-up table approach. By the way, since it might be a long string, I wouldn't consider to convert the string to integer and process the format conversion, as a long string might be greater than MAX_INT (or other integer data types).

For example:

0xA1 => 10100001
11110001 => 0xF1

PS: My project is using Boost 1.44, a bit out-dated. So if the utility is from Boost, hopefully it's available in 1.44.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...