字符串和二进制串相互转换(C++)
作者:互联网
一、字符转化成二进制
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
//字符转化成二进制串
bitset<8> bits = bitset<8>('a');
bitset<1> tmp;
//二进制翻转
for(int i=0;i<4;i++)
{
tmp[0] = bits[i];
bits[i] = bits[7-i];
bits[7-i] = tmp[0];
}
//输出
for(int i=0;i<8;i++)
cout<<bits[i];
}
二、字符串转化成二进制字符串
#include <iostream>
#include <bitset>
#include <string>
#include <algorithm>
using namespace std;
//将8位字符串转化为64bit
string StrToBitStr(string str)
{
bitset<64> bstr ;
for(int i=0;i<8;i++)
{
bitset<8> bits = bitset<8>(str[i]);
cout<<str[i]<<endl;
for(int j = 0;j<8;j++)
{
bstr[i*8+j] = bits[7-j];
}
}
string s = bstr.to_string();
//添加一个翻转操作
reverse(begin(s),end(s));
return s;
}
int main()
{
string bstr = StrToBitStr("generate");
cout<<bstr<<endl;
}
三、二进制字符串转化成字符串
#include <iostream>
#include <bitset>
#include <string>
#include <algorithm>
using namespace std;
//将8位字符串转化为64bit
string StrToBitStr(string str)
{
bitset<64> bstr ;
for(int i=0;i<8;i++)
{
bitset<8> bits = bitset<8>(str[i]);
cout<<str[i]<<endl;
for(int j = 0;j<8;j++)
{
bstr[i*8+j] = bits[7-j];
}
}
string s = bstr.to_string();
//添加一个翻转操作
reverse(begin(s),end(s));
return s;
}
//将64bit二进制字符串转化为字符串
string BitStrToStr(string bstr)
{
string str="";
//每八位转化成十进制,然后将数字结果转化成字符
int sum;
for(int i=0;i<bstr.size();i+=8)
{
sum=0;
for(int j=0;j<8;j++)
if(bstr[i+j] == '1')
sum = sum*2+1;
else
sum = sum*2;
str =str+char(sum);
}
return str;
}
int main()
{
string bstr = StrToBitStr("generate");
cout<<bstr<<endl;
cout<<BitStrToStr(bstr)<<endl;
}
标签:string,二进制,C++,int,bitset,bstr,字符串,include,bits 来源: https://blog.csdn.net/xiaoyujiale/article/details/112424668