首页
学习
活动
专区
工具
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}

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

相关·内容

C++实现对16进制字符串和字节数组的tea加密和解密算法

TEA(Tiny Encryption Algorithm) 是一种简单高效的加密算法,以加密解密速度快,实现简单著称。算法真的很简单,TEA算法每一次可以操作64-bit(8-byte),采用128-bit(16-byte)作为key,算法采用迭代的形式,推荐的迭代轮数是64轮,最少32轮。 TEA 算法最初是由剑桥计算机实验室的 David Wheeler 和 Roger Needham 在 1994 年设计的。该算法使用 128 位的密钥为 64 位的信息块进行加密,它需要进行 64 轮迭代,尽管作者认为 32 轮已经足够了。该算法使用了一个神秘常数δ作为倍数,它来源于黄金比率,以保证每一轮加密都不相同。但δ的精确值似乎并不重要,这里 TEA 把它定义为 δ=「(√5 - 1)231」(也就是程序中的 0×9E3779B9)。 下面是维基百科中个关于该算法的C语言描述的代码片段,如下:

02
领券