将二进制bitset转换为十六进制(C ++)

时间:2013-10-19 01:52:03

标签: c++

有没有一种简单的方法将二进制位集转换为十六进制?该函数将用于CRC类,仅用于标准输出。

我已经考虑过使用to_ulong()将bitset转换为整数,然后使用switch case将整数10 - 15转换为A - F.但是,我正在寻找一些更简单的东西。

我在网上找到了这段代码:

#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;
}

它运行良好,但我需要将输出存储在变量中,然后将其返回到函数调用,而不是直接将其发送到标准输出。

我试图改变代码,但一直遇到错误。有没有办法更改代码以将十六进制值存储在变量中?或者,如果有更好的方法,请告诉我。

谢谢。

3 个答案:

答案 0 :(得分:6)

您可以将输出发送到std::stringstream,然后将结果字符串返回给调用者:

stringstream res;
res << hex << uppercase << set.to_ulong();
return res.str();

这会产生std::string类型的结果。

答案 1 :(得分:2)

以下是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

答案 2 :(得分:0)

这是C ++的简单替代方法:

bitset <32> data; /*Perform operation on data*/ cout << "data = " << hex << data.to_ulong() << endl;