0

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"

1
  • Is there a problem with our answers? Commented May 3, 2011 at 4:20

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

-1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.