字符串与二进制编码/base64编码互相转换的小工具

2 篇文章 0 订阅

网上东西太多了,原来不想写的,网上东西太多太杂了,找半天不一定有用,所以本文主要保存两个简单的小工具,后期也会进行扩展和完善。

字符串与二进制的互转:

bool StringToBianery2(const string& input, string* output) {
    for(int i = 0 ; i < input.length(); i++){
        string temprst = "";
        int temp = (int)input[i];
        int count = 0;
        while(temp > 0){
            if(temp %  2 == 0){
                temprst += '0';
            }else{
                temprst += '1';
            }
            temp /= 2;
            count++;
        }
        if(count < 8){
            for(int j = 0 ; j < (8-count); j++){
                temprst += '0';
            }
        }
        //反转
        int index = 0;
        string temprst2 = "";
        for(int j = 7; j >= 0; j--){
            temprst2 += temprst[j];
            index++;
        }
        *output += temprst2;
    }
    return output->empty() == false;
}
bool Bianery2ToString(const string& input, string* output){
    int strlen = 0;
    while(strlen < input.length()){
        int temp = 0 , count = 7;
        for(int j = strlen; j < strlen+8; j++){
            if(input[j] == '1'){
                temp += pow(2, count);
            }
            count--;
        }
        char rsttemp = (char)temp;
        *output += rsttemp;
        strlen = strlen + 8;
    }
    return output->empty() == false;
}

字符串与base64编码的互转

boost中有实现base64编码的方式,所以做一个小封装

bool Base64Encode(const string& input, string* output) {
    typedef boost::archive::iterators::base64_from_binary<boost::archive::iterators::transform_width<string::const_iterator, 6, 8> > Base64EncodeIterator;
    stringstream result;
    copy(Base64EncodeIterator(input.begin()) , Base64EncodeIterator(input.end()), ostream_iterator<char>(result));
    size_t equal_count = (3 - input.length() % 3) % 3;
    for (size_t i = 0; i < equal_count; i++) {
        result.put('=');
    }
    *output = result.str();
    return output->empty() == false;
}
bool Base64Decode(const string& input, string* output) {
    typedef boost::archive::iterators::transform_width<boost::archive::iterators::binary_from_base64<string::const_iterator>, 8, 6> Base64DecodeIterator;
    stringstream result;
    try {
        copy(Base64DecodeIterator(input.begin()) , Base64DecodeIterator(input.end()), ostream_iterator<char>(result));
    } catch(...) {
        return false;
    }
    *output = result.str();
    return output->empty() == false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值