0

您好,我想一次将字符串中的两个字符转换为二进制?我怎样才能通过应用简单的算术来做到这一点(即通过制作我自己的函数?)

例如:我们的字符串是 = 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 介于两者之间。直接从字符到二进制......这可能吗?

4

3 回答 3

3

如果您正在寻找一种以文本方式表示字符的二进制表示的方法,那么这里有一个小例子来说明如何做到这一点:

c一个打印to二进制表示的小函数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

如果您想将字符对的二进制数存储在 a 中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);
}
于 2013-11-07T19:16:19.900 回答
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;
}
于 2013-11-07T19:10:10.400 回答
0

我猜你正在寻找的东西是铸造。试试这样:

char *string = "hello world ";
short *tab = (short*)string;

for(int i = 0; i < 6; i++)
    std::cout << tab[i] << std::endl;
于 2013-11-07T19:06:20.713 回答