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've thought about using to_ulong() to convert the bitset to a integer, then converting the integers 10 - 15 to A - F using a switch case. However, I'm looking for something a little simpler.
I found this code on the internet:
#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.
To convert a binary number to a hexadecimal number, we take four digits from the right-most part of the binary form to divide it into two sets. If there are less than four digits on the left, add extra zeros to the binary number. Then, the number is multiplied by ( 2 n 2^n 2n).
First convert this into decimal number: = (1101010)2 = 1x26+1x25+0x24+1x23+0x22+1x21+0x20 = 64+32+0+8+0+2+0 = (106)10 Then, convert it into hexadecimal number = (106)10 = 6x161+10x160 = (6A)16 which is answer.
You can send the output to a std::stringstream
, and then return the resultant string to the caller:
stringstream res;
res << hex << uppercase << set.to_ulong();
return res.str();
This would produce a result of type std::string
.
Here is an alternative for C:
unsigned int bintohex(char *digits){
unsigned int res=0;
while(*digits)
res = (res<<1)|(*digits++ -'0');
return res;
}
//...
unsigned int myint=bintohex("11001111");
//store value as an int
printf("%X\n",bintohex("11001111"));
//prints hex formatted output to stdout
//just use sprintf or snprintf similarly to store the hex string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With