您好我想将字符串中的两个字符一次转换为二进制文件吗?我怎么能通过应用简单的算术(即通过制作我自己的函数?)来做到这一点。
例如:我们的字符串是= hello world
:
所需的输出(一次两个字符):
he // need binaryform of 0's and 1's (16 bits for 2 characters 'h' and 'e'
ll // similarly
o(space) // single space also counts as a character with 8 zero bit in binary.
wo
rl
d(space) // space equals a character again with 8 zero bits
如何解决这个问题。我不想要任何ascii介于两者之间。直接从字符到二进制......这可能吗?
答案 0 :(得分:3)
如果您正在寻找一种文本表示字符二进制表示的方法,那么这里有一个小例子,说明如何做到这一点:
一个小函数,它打印出c
到std::cout
的二进制表示形式(仅适用于标准ASCII字母):
void printBinary(char c) {
for (int i = 7; i >= 0; --i) {
std::cout << ((c & (1 << i))? '1' : '0');
}
}
像这样使用它(只打印出一对字符):
std::string s = "hello "; // Some string.
for (int i = 0; i < s.size(); i += 2) {
printBinary(s[i]);
std::cout << " - ";
printBinary(s[i + 1]);
std::cout << " - ";
}
输出:
01101000 - 01100101 - 01101100 - 01101100 - 01101111 - 00100000 -
修改强>
实际上,使用std::bitset
这就是所需要的:
std::string s = "hello "; // Some string.
for (int i = 0; i < s.size(); i += 2) {
std::cout << std::bitset<8>(s[i]) << " ";
std::cout << std::bitset<8>(s[i + 1]) << " ";
}
输出:
01101000 01100101 01101100 01101100 01101111 00100000
如果你想在std::vector
中存储字符对的二进制数,如评论中所述,那么这样就可以了:
std::vector<std::string> bitvec;
std::string bits;
for (int i = 0; i < s.size(); i += 2) {
bits = std::bitset<8>(s[i]).to_string() + std::bitset<8>(s[i + 1]).to_string();
bitvec.push_back(bits);
}
答案 1 :(得分:1)
使用C ++ STL中的 bitset 类可以快速轻松地完成此任务。
以下是您可以使用的功能:
#include <string>
#include <bitset>
string two_char_to_binary(string s) // s is a string of 2 characters of the input string
{
bitset<8> a (s[0]); // bitset constructors only take integers or string that consists of 1s and 0s e.g. "00110011"
bitset<8> b (s[1]); // The number 8 represents the bit depth
bitset<16> ans (a.to_string() + b.to_string()); // We take advantage of the bitset constructor that takes a string of 1s and 0s and the concatenation operator of the C++ string class
return ans.to_string();
}
样本用法:
using namespace std;
int main(int argc, char** argv)
{
string s = "hello world";
if(s.length() % 2 != 0) // Ensure string is even in length
s += " ";
for(int i=0; i<s.length(); i += 2)
{
cout << two_char_to_binary(s.substr(i, 2)) << endl;
}
return 0;
}
答案 2 :(得分:0)
我猜你要找的东西就是施法。试试这样:
char *string = "hello world ";
short *tab = (short*)string;
for(int i = 0; i < 6; i++)
std::cout << tab[i] << std::endl;