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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19461478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:50:41  来源:igfitidea点击:

Convert binary bitset to hexadecimal (C++)

c++

提问by navig8tr

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.

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

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.

我想过使用 to_ulong() 将位集转换为整数,然后使用 switch case 将整数 10 - 15 转换为 A - F。但是,我正在寻找更简单的东西。

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.

谢谢你。

采纳答案by dasblinkenlight

You can send the output to a std::stringstream, and then return the resultant string to the caller:

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

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

This would produce a result of type std::string.

这将产生类型为 的结果std::string

回答by technosaurus

Here is an alternative for C:

这是 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

回答by dumb_pawn

Here is the easy alternative for C++:

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

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

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