一次C++两个字符的字符到二进制转换,以获得 16 位二进制形式

character to binary conversion in C++ two characters at a time to get 16 bit binary form

本文关键字:字符 二进制 转换 C++ 两个 一次      更新时间:2023-10-16

您好,我想一次将字符串中的两个字符转换为二进制? 我如何通过应用简单的算术(即通过制作自己的函数?

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

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

一个小函数,用于打印出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);
}

这可以使用 C++ STL 中的位集类快速轻松地完成。

以下是您可以使用的函数:

#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;
}

我想你要找的东西是铸造。尝试如下:

char *string = "hello world ";
short *tab = (short*)string;
for(int i = 0; i < 6; i++)
    std::cout << tab[i] << std::endl;