使用C++将字符转换为字节表示
Converting chars to byte representation using C++
将字符转换为无符号二进制表示形式(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;
}
相关文章:
- 是否可以保证按字节的零 int 是零的表示形式?
- 如何获取 BITMAPFILEHEADER 和 BITMAPINFOHEADER 的字节表示形式?
- C++ CUDA:如何将字节表示为字符或字符集?
- 如何在 c++ 中将字节转换为 ASCII 十六进制表示形式?
- 我想发送固定数量的字节来表示可以解析为整数值的数值
- 如何编写一个字节表示为c 中的文件
- 计算表示有符号整数所需的最小字节数
- 如何将一个数字(大于8个字节)从字符阵列转换为其ASCII表示
- 来自向量 c++ 中的字节表示
- std::wstring中ASCII符号的字节表示,具有不同的语言环境
- 变量的字节表示的意外结果
- 使用 uint8_t 或 char 来表示以字节排列的二进制数据更好吗?
- 显示非常大的数字,用字节[]表示
- 在std::向量中表示原始字节的最佳方式
- C++ 分配期间 NaN 字节表示形式发生变化
- 使用C++将字符转换为字节表示
- 在C/ c++中有一个简短的字节表示法吗?
- Visual Studio 2008中命令行参数的2字节表示
- 数字的字节表示
- C++在不进行*序列化的情况下获取unsodered_set*的字节表示