9

有没有一种简单的方法可以将二进制位集转换为十六进制?该函数将在 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;
}

它工作得很好,但我需要将输出存储在一个变量中,然后将其返回给函数调用,而不是直接将其发送到标准输出。

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

谢谢你。

4

3 回答 3

8

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

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

这将产生 type 的结果std::string

于 2013-10-19T01:55:47.083 回答
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
于 2013-10-19T03:03:43.160 回答
1

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

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

于 2018-09-19T15:59:06.957 回答