网上东西太多了,原来不想写的,网上东西太多太杂了,找半天不一定有用,所以本文主要保存两个简单的小工具,后期也会进行扩展和完善。
字符串与二进制的互转:
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;
}
|