从std::vector<bool>
获取字节是指将std::vector<bool>
中的元素转换为字节(unsigned char
)。这里是一个简单的方法,将std::vector<bool>
转换为std::vector<unsigned char>
:
#include<iostream>
#include<vector>
std::vector<unsigned char> convertVector(const std::vector<bool>& input) {
std::vector<unsigned char> output;
int byte = 0;
int bit_index = 0;
for (const bool bit : input) {
if (bit_index == 8) {
output.push_back(byte);
byte = 0;
bit_index = 0;
}
byte |= static_cast<unsigned char>(bit) << (7 - bit_index);
bit_index++;
}
if (bit_index > 0) {
output.push_back(byte);
}
return output;
}
int main() {
std::vector<bool> input = {1, 0, 1, 1, 0, 1, 0, 1};
std::vector<unsigned char> output = convertVector(input);
for (const unsigned char byte : output) {
std::cout<< static_cast<int>(byte) << " ";
}
return 0;
}
这个代码示例将std::vector<bool>
中的元素转换为字节,并将结果存储在std::vector<unsigned char>
中。在这个例子中,输入向量{1, 0, 1, 1, 0, 1, 0, 1}
将被转换为字节向量{192}
。
领取专属 10元无门槛券
手把手带您无忧上云