将字符串转换为表示这些字符的1和0字符串
Converting a string of characters to a string of 1s and 0s that represent those characters
我想将一个字符串(显然每个字节)转换为一个1和0的字符串,这些字符串表示每个字符的二进制代码,首先是最低有效位。
例如,字符串"Ab3"将变为"10000010"表示"A","01000110"表示"b","11001100"表示"3"。注意所有的字符都是8位,我认为是这样的,因为字符需要有所有的8位才能正确保存。如果这是真的,那么这个例子的整个字符串应该是"10000000100011011001100"
我想不出如何用比特移位运算符来实现这一点,因为你不能把每个比特都转换成一个字符,但我知道一定有办法做到这一点。
注意:我不允许在此项目中使用位集(或任何STL)。
谢谢你的帮助!
stringstream ss;
for(char c: std::string("Ab3"))
ss << std::bitset<8>(c);
cout << ss.str();
使用std::bitset
:
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
std::string bits;
std::string s = "abcd";
for (std::string::iterator it = s.begin(); it != s.end(); it++) {
std::bitset<CHAR_BIT> bset;
bset |= (unsigned char)*it;
bits += bset.to_string();
}
std::cout << bits << std::endl;
return 0;
}
编辑:根据愚蠢的限制重写相关部分:
std::string bits;
std::string s = "abcd";
for (std::string::iterator it = s.begin(); it != s.end(); it++) {
unsigned char c = *it;
for (int i = CHAR_BIT - 1; i >= 0; i--)
bits += '0' + ((c >> i) & 1);
}
std::cout << bits << std::endl;
我想不出如何用比特移位运算符来实现这一点,因为你不能把每个比特都转换成一个字符,但我知道一定有办法做到这一点。
也许多看一点比特移位?这不是STL函数。我敢打赌,你的教授正试图把你推向低水平的钻头操作。
您将需要使用位移位和掩码。
void output_binary_rep(const std::string text&, std::ostream& output)
{
// Look up CHAR_BIT, which contains the number of bits per character.
const unsigned int length = text.length();
// For each character in the string, do:
for (unsigned int i = 0U; i < length; ++i)
{
// For each bit in the character, output a '1' or '0'.
for (unsigned int j = 0; j < CHAR_BIT; ++j)
{
// Isolate a bit, from MSB to LSB, using
// a 1 left shited by a number of bits.
if (text[i] & (1 << (CHAR_BIT - j - 1)))
{
output << "1";
}
else
{
output << "0";
}
}
}
}
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度