Convert binary bitset to hexadecimal

Is there a simple way to convert a binary bitset to hexadecimal? The function will be used in a CRC class and will only be used for standard output.

I found this code on the internet:
1
2
3
4
5
6
7
8
9
10
#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;
}


It works great, but I need to store the output in a variable then return it to the function call rather than send it directly to standard out.

I've tried to alter the code but keep running into errors. Is there a way to change the code to store the hex value in a variable? Or, if there's a better way to do this please let me know.

Thank you.
closed account (o3hC5Di1)
Hi there,

You could output it to a stringstream, then convert it to a number:

1
2
3
4
5
6
7
string binary_str("11001111");
bitset<8> set(binary_str);	

std::stringstream ss;
int number;
ss << hex << set.to_ulong() << endl;
ss >> number;


Don't forget to #include <sstream> .

Working example: http://coliru.stacked-crooked.com/a/6dc8dc0c4c2442a3

Hope that helps.

All the best,
NwN
Last edited on
Topic archived. No new replies allowed.