将二进制字符串转换为ASCII字符串(C ++) [英] Convert a string of binary into an ASCII string (C++)
问题描述
我有一个包含32位二进制数的字符串变量.将二进制表示的这4个字符(8位为1个字符)转换回其ASCII字符的最佳方法是什么?
I have a string variable containing 32 bits of binary. What would be the best way to convert these 4 characters (8 bits is one character) represented by the binary back into their ASCII characters?
例如,一个变量包含"01110100011001010110111001101110100",应将其转换回字符串"test".
For example, a variable contains "01110100011001010111001101110100" which should be converted back into the string "test".
推荐答案
如果您使用的是C ++ 11,则为另一种选择:
An alternative if you're using C++11:
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
int main()
{
std::string data = "01110100011001010111001101110100";
std::stringstream sstream(data);
std::string output;
while(sstream.good())
{
std::bitset<8> bits;
sstream >> bits;
char c = char(bits.to_ulong());
output += c;
}
std::cout << output;
return 0;
}
请注意,位集是C ++ 11的一部分.
Note that bitset is part of C++11.
还请注意,如果数据格式不正确,当sstream.good()返回false时,结果将被静默截断.
Also note that if data is not well formed, the result will be silently truncated when sstream.good() returns false.
这篇关于将二进制字符串转换为ASCII字符串(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!