有没有一种简单的方法将二进制位集转换为十六进制?该函数将用于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;
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但我需要将输出存储在变量中然后将其返回到函数调用而不是直接将其发送到标准输出.
我试图改变代码,但一直遇到错误.有没有办法更改代码以将十六进制值存储在变量中?或者,如果有更好的方法,请告诉我.
谢谢.
您可以将输出发送到a std::stringstream,然后将结果字符串返回给调用者:
stringstream res;
res << hex << uppercase << set.to_ulong();
return res.str();
Run Code Online (Sandbox Code Playgroud)
这会产生类型的结果std::string.