Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary bitset to hexadecimal (C++)

Tags:

c++

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.

like image 300
navig8tr Avatar asked Oct 19 '13 01:10

navig8tr


People also ask

How to convert a binary number to hexadecimal in c++?

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).

How do you convert 16 bit binary to hexadecimal?

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.


2 Answers

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.

like image 85
Sergey Kalinichenko Avatar answered Oct 11 '22 22:10

Sergey Kalinichenko


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
like image 31
technosaurus Avatar answered Oct 11 '22 21:10

technosaurus