C++ 在十六进制格式和二进制格式之间转换字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18310952/
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
Convert strings between hex format and binary format
提问by Stan
Is there any utility or library provides a simple function to convert a string between hex/binary format? I've been searching on SO and currently using look-up table approach. By the way, since it might be a long string, I wouldn't consider to convert the string to integer and process the format conversion, as a long string might be greater than MAX_INT (or other integer data types).
是否有任何实用程序或库提供了一个简单的函数来在十六进制/二进制格式之间转换字符串?我一直在搜索 SO,目前正在使用查找表方法。顺便说一下,由于它可能是一个长字符串,我不会考虑将字符串转换为整数并处理格式转换,因为长字符串可能大于 MAX_INT(或其他整数数据类型)。
For example:
例如:
0xA1 => 10100001
11110001 => 0xF1
PS: My project is using Boost 1.44, a bit out-dated. So if the utility is from Boost, hopefully it's available in 1.44.
PS:我的项目使用的是Boost 1.44,有点过时了。因此,如果该实用程序来自 Boost,则希望它在 1.44 中可用。
回答by Silex
You can use a combination of std::stringstream, std::hexand std::bitsetto convert between hex and binary in C++03.
在 C++03中std::stringstream,您可以使用,std::hex和的组合std::bitset在十六进制和二进制之间进行转换。
Here's an example:
下面是一个例子:
#include <iostream>
#include <sstream>
#include <bitset>
#include <string>
using namespace std;
int main()
{
string s = "0xA";
stringstream ss;
ss << hex << s;
unsigned n;
ss >> n;
bitset<32> b(n);
// outputs "00000000000000000000000000001010"
cout << b.to_string() << endl;
}
EDIT:
编辑:
About the refined question, here's a code example about converting between hex strings and binary strings (you can refactor with a helper function for the hex char<>bits part, and use a map or a switch instead, etc).
关于精炼的问题,这里有一个关于在十六进制字符串和二进制字符串之间转换的代码示例(您可以使用十六进制字符<>位部分的辅助函数进行重构,并改用映射或开关等)。
const char* hex_char_to_bin(char c)
{
// TODO handle default / error
switch(toupper(c))
{
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'B': return "1011";
case 'C': return "1100";
case 'D': return "1101";
case 'E': return "1110";
case 'F': return "1111";
}
}
std::string hex_str_to_bin_str(const std::string& hex)
{
// TODO use a loop from <algorithm> or smth
std::string bin;
for(unsigned i = 0; i != hex.length(); ++i)
bin += hex_char_to_bin(hex[i]);
return bin;
}
回答by ilent2
The following code includes two functions that will do exactly as you desire. This is based on the answer by Silex but with a few extra string operations to match the example output you gave in your question.
下面的代码包括两个完全按照您的意愿执行的函数。这是基于 Silex 的答案,但有一些额外的字符串操作来匹配您在问题中给出的示例输出。
#include <iostream>
#include <sstream>
#include <bitset>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
const unsigned g_unMaxBits = 32;
string Hex2Bin(const string& s)
{
stringstream ss;
ss << hex << s;
unsigned n;
ss >> n;
bitset<g_unMaxBits> b(n);
unsigned x = 0;
if (boost::starts_with(s, "0x") || boost::starts_with(s, "0X")) x = 2;
return b.to_string().substr(32 - 4*(s.length()-x));
}
string Bin2Hex(const string& s)
{
bitset<g_unMaxBits> bs(s);
unsigned n = bs.to_ulong();
stringstream ss;
ss << hex << n;
return "0x" + boost::to_upper_copy(ss.str());
}
int main()
{
cout << "0xA1 => " << Hex2Bin("0xA1") << endl;
cout << "B3 => " << Hex2Bin("B3") << endl;
cout << "11110001 => " << Bin2Hex("11110001") << endl;
return 0;
}
回答by HaSeeB MiR
The simplest solution without using bitsetor any library, only using shift operators and std::hexto convert the whole hex-string.
最简单的解决方案,不使用bitset或任何库,只使用移位运算符和std::hex来转换整个hex-string。
sample code to convert hex-string to binary-digits :
将十六进制字符串转换为二进制数字的示例代码:
string s = "FF 0F F0 C3 10";
stringstream ss;
ss << hex << s;
unsigned int n;
while(ss >> n){
for (int i = 8 -1; i >= 0; i--)
cout << ((n >> i) & 1) ? "1" : "0";
cout << std::endl;
}
sample output :
样本输出:
11111111
00001111
11110000
11000011
00001010
回答by Anant Prakash
If you want a concise solution in plain c++11. Here you go:
如果你想要一个简单的 c++11 简洁的解决方案。干得好:
string hextobin(const string &s){
string out;
for(auto i: s){
uint8_t n;
if(i <= '9' and i >= '0')
n = i - '0';
else
n = 10 + i - 'A';
for(int8_t j = 3; j >= 0; --j)
out.push_back((n & (1<<j))? '1':'0');
}
return out;
}
string bintohex(const string &s){
string out;
for(uint i = 0; i < s.size(); i += 4){
int8_t n = 0;
for(uint j = i; j < i + 4; ++j){
n <<= 1;
if(s[j] == '1')
n |= 1;
}
if(n<=9)
out.push_back('0' + n);
else
out.push_back('A' + n - 10);
}
return out;
}
This would work for any length of string with no padding required. Should be pretty fast since there's no long switch cases and bit operations are fast.
这适用于任何长度的字符串,无需填充。应该很快,因为没有很长的 switch case 并且位操作很快。
Example usage:
用法示例:
string s = "FF11";
string b = hextobin(s);
cout << b << endl; // prints 1111111100010001
string h = bintohex(b);
cout << h << endl; // prints FF11

