我有一个被翻译成5位形式的文本。如何替换一些位,然后用改变的位输出文本?这里我的文本Hello输出01000 00101 01100 01100 01111有必要用相反的位替换任何位,然后以位形式输入我们更改的文本
这段代码
#include <iostream>
#include <string>
#include <bitset>
std::string toBinary(std::string const &str) {
std::string binary = "";
for (char const &c: str) {
binary += std::bitset<5>(c).to_string() + ' ';
}
return binary;
}
int main()
{
std::string str = "Hello world";
std::string binary = toBinary(str);
std::cout << binary << std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <bitset>
#include <vector>
std::string toString(std::string binary1)
{
// use an array to store each letter's representation separately
std::vector<std::string> arr;
int i = 0;
while (i < binary1.length())
{
std::string x = "";
while (binary1[i] != ' ')
{
x += binary1[i];
i++;
}
arr.push_back(x);
i++;
}
// convert the bits back to string
std::string binary2 = "";
for (int i = 0; i < arr.size(); i++)
{
if (arr[i] == "00000")
{
binary2 += " ";
}
else
binary2 += char(std::bitset<5>(arr[i]).to_ulong() + 64);
}
return binary2;
}
std::string toBinary(std::string const &str)
{
std::string binary = "";
for (char const &c : str)
{
binary += std::bitset<5>(c).to_string() + ' ';
}
return binary;
}
int main()
{
std::string str = "Hello world";
std::string binary1 = toBinary(str);
std::cout << binary1 << std::endl;
// change certain bits
// for instance, we're changing the first bit and the 9th bit;
std::string str1, str2;
str1 = str2 = binary1;
str1[0] = '1';
str2[9] = '1';
std::cout << toString(str1) << std::endl;
std::cout << toString(str2) << std::endl;
return 0;
}
输出:01000 00101 01100 01100 01111 00000 10111 01111 10010 01100 00100
XELLO WORLD
HGLLO WORLD