首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从std :: vector <bool>获取字节

std::vector<bool>获取字节是指将std::vector<bool>中的元素转换为字节(unsigned char)。这里是一个简单的方法,将std::vector<bool>转换为std::vector<unsigned char>

代码语言:cpp
复制
#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}

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

7分23秒

第二十章:类的加载过程详解/64-加载完成的操作及二进制的获取方式

领券