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

时间:2015-11-09 19:48:42

标签: c++ binary char

将char转换为无符号二进制表示(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;
}

我假设将char设置为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;
} 

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

2 个答案:

答案 0 :(得分:0)

std::string::append()将字符添加到字符串的 end 。所以你要按 reverse 顺序打开这些位:LSB是第一个字符,反之亦然。试试这个:binary.insert (0, 1, (code % 2 == 1) ? '1' : '0');

答案 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;
}