使用C++将字符转换为字节表示

Converting chars to byte representation using C++

本文关键字:字节 表示 转换 字符 C++ 使用      更新时间:2023-10-16

将字符转换为无符号二进制表示形式(MSB为0的字节)的最有效但最简单的方法是什么?我有一个这样设置的方法:

string AsciiToBinary(char value) {
        string binary = "";
        int code = value;
        while (code > 0) {
                if ((code % 2) == 1) {
                        binary.append("1", 1);
                } else {
                        binary.append("0", 1);
                }
                code = code / 2;
        }
        return binary;
}

我假设将int设置为char会将char的ASCII值设置为int。但是,我的结果与ASCII表不匹配。我正在按如下方式实现此功能:

char head = stack.pop();
int code = head; // do not need to parse
string binary;
while (!stack.isEmpty()) {
        binary = AsciiToBinary(code);
        outfile << binary << endl;
        binary.clear();
        head = stack.pop();
        code = head;
} 

我已将所有字符存储在一个堆栈中
感谢您提供的信息和指导。

std::string::append()将字符添加到字符串的末尾。因此,您将按反向顺序放置位:LSB是第一个字符,反之亦然。试试这个:binary.insert (0, 1, (code % 2 == 1) ? '1' : '0');

这个方法效果很好,对于所有感兴趣并学习C++的人来说都是可编辑的:

using namespace std; // bad for updates
#include <string>
string AsciiToBinary(char value) {
        string binary = "";
        unsigned int code = value;
        unsigned int chk = value;
        while (code > 0) {
                if ((code & 1) == 1) {
                        binary.append("1", 1);
                } else {
                        binary.append("0", 1);
                }
                code = code / 2;
        }
        reverse(binary.begin(), binary.end());
        if (chk < 64) {
                binary.insert(0, "00");
        } else {
                binary.insert(0, "0");
        }
        return binary;
}