Mirza
Mirza

Reputation: 645

Converting a string representing binary to a string representing equivalent hex

So i have a string x = "10101" and i need to put into any string y the hex value of the binary in x. So if x="10101" then y="0x15"

Upvotes: 0

Views: 1235

Answers (3)

Elalfer
Elalfer

Reputation: 5338

You should probably use strtol ( http://en.wikipedia.org/wiki/Strtol ) function with the base 2 to convert x to the integer and then use sprintf to format the result string.

Upvotes: 1

Adam Casey
Adam Casey

Reputation: 1620

I don't want to provide you with the complete answer.

That said, the basic idea should be fill the start of the string with up to 3 zero's so that you can split the string into substrings with a length of 4. This can then easily be turned into hex by a variety of ways, the easiest being just using a switch case statement. There would only be 16 cases'

Upvotes: -1

Rob
Rob

Reputation: 2786

The simplest way to do this is using a [bitset][1]:

#include <iostream>
#include <string>
#include <bitset>

using namespace std;
int main(){
    string binary_str("11001111");
    bitset<8> set(binary_str);  
    cout << hex << set.to_ulong() << endl;
}

But I read that it's not the most efficient way... Depends on what you whant. Remember that premature optimisation is the root of all evil.

Upvotes: 4

Related Questions