废话不多说上代码
#include <iostream>
#include <vector>
#include <string>
void SecToStr(const std::string strSrc, std::string& strDst)
{
for (size_t j = 0; j < strSrc.size(); j = j+8)
{
std::string strTmp = strSrc.substr(j, 8);
unsigned int i = 0;
const char* pch = strTmp.c_str();
while (*pch == '0' || *pch == '1') {
i <<= 1;
i |= *pch++ - '0';
}
char a[2] = {0, 0};
a[0] = i;
a[1] = '\0';
std::string strTmp2 = a;
strDst.append(strTmp2);
}
}
void StrToSec(const std::string& strSrc, std::string& strDst)
{
std::string str = strSrc;
for (int i = 0;i < strSrc.size();++i) {
for (int j = 7;j >= 0;--j) {
if (str[i] >> j & 0x1) {
strDst.append("1");
}
else {
strDst.append("0");
}
}
}
}
int main()
{
std::string str = "万剑归总,hello, world!";
std::cout << str << "\n";
std::string strDst = "";
StrToSec(str, strDst);
std::cout << strDst << "\n";
std::string dst1 = "";
SecToStr(strDst, dst1);
std::cout << dst1 << "\n";
}