将 bool[] 转换为 byte[] [英] Convert bool[] to byte[]

查看:99
本文介绍了将 bool[] 转换为 byte[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List,我想将其转换为 byte[].我该怎么做呢?list.toArray() 创建一个 bool[].

I have a List<bool> which I want to convert to a byte[]. How do i do this? list.toArray() creates a bool[].

推荐答案

这里有两种方法,取决于你是想把位打包成字节,还是和原始位一样多:

Here's two approaches, depending on whether you want to pack the bits into bytes, or have as many bytes as original bits:

    bool[] bools = { true, false, true, false, false, true, false, true,
                     true };

    // basic - same count
    byte[] arr1 = Array.ConvertAll(bools, b => b ? (byte)1 : (byte)0);

    // pack (in this case, using the first bool as the lsb - if you want
    // the first bool as the msb, reverse things ;-p)
    int bytes = bools.Length / 8;
    if ((bools.Length % 8) != 0) bytes++;
    byte[] arr2 = new byte[bytes];
    int bitIndex = 0, byteIndex = 0;
    for (int i = 0; i < bools.Length; i++)
    {
        if (bools[i])
        {
            arr2[byteIndex] |= (byte)(((byte)1) << bitIndex);
        }
        bitIndex++;
        if (bitIndex == 8)
        {
            bitIndex = 0;
            byteIndex++;
        }
    }

这篇关于将 bool[] 转换为 byte[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆