C++实现二进制码流和字符串码流互转

废话不多说上代码

#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";
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值