我必须将 std::string
复制到 ASCII ... 但内存中只有 7bit ASCII。所以这个 8 字符的字符串应该适合这个 7 字节/56 位数组。
std::string str = "12345678";
unsigned char ascii_destination[7];
我可以抓取 str
中的每个字符并通过位操作将其复制到它的目的地,但我想知道是否有更优雅的方法可以将更长的字符串转换为内存中的 7 位?而且我还没有找到任何内置函数...谢谢!
最佳答案
因为你只有 56 位,所以你可以使用 64 位整数作为中间存储:
uin64_t temp = 0;
// Add 7 bits to temp, 8 times
for (int i = 0; i < 8; ++i)
temp = (temp << 7) | str[i];
// Remove 8 bits from temp, 7 times
for (int i = 0; i < 7; ++i)
{
ascii_destination[i] = (uint8_t)(temp & 0xff);
temp >>= 8;
}
(除非我完全理解错了你真正想要的)
关于c++ - 将 std::string 复制到 7 位 ASCII 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34336581/