You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将不规则长度bool[]按每个bool对应1位转换为short[]数组

实现方案

每个short占16个比特位,转换逻辑如下,可直接运行:

using System;
using System.Collections;
using System.Collections.Generic;

public static class ArrayConverter
{
    public static short[] BoolArrayToShortArray(bool[] bools)
    {
        // 补位到总比特数为16的整数倍,不足末尾补false(对应比特0)
        int padLength = bools.Length % 16 == 0 ? 0 : 16 - (bools.Length % 16);
        List<bool> boolList = new List<bool>(bools);
        boolList.AddRange(new bool[padLength]);

        // bool数组转BitArray再转字节数组
        BitArray bitArray = new BitArray(boolList.ToArray());
        byte[] byteBuffer = new byte[bitArray.Length / 8];
        bitArray.CopyTo(byteBuffer, 0);

        // 每2个字节转1个short
        short[] result = new short[byteBuffer.Length / 2];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = BitConverter.ToInt16(byteBuffer, i * 2);
        }
        return result;
    }
}

原有代码问题修正说明

你之前的代码存在几个错误:

  • short数组长度计算错误:bytes.Length%16 应该改为 bytes.Length / 2,1个short固定占用2个字节
  • BitConverter.ToInt16 没有传偏移参数,每次都从字节数组第0位读取,导致所有short值完全相同
  • 缺少BitArray转byte[]的实现,.NET原生BitArray提供了CopyTo方法可直接转换为字节数组,无需自己手写转换逻辑

测试用例

// 测试1:长度为2的bool数组
bool[] test1 = new[] { true, true };
short[] res1 = ArrayConverter.BoolArrayToShortArray(test1);
Console.WriteLine(res1[0]); // 输出3,对应二进制 0000000000000011

// 测试2:长度为6的bool数组
bool[] test2 = new bool[] { true, true, true, false, true, false };
short[] res2 = ArrayConverter.BoolArrayToShortArray(test2);
Console.WriteLine(res2[0]); // 输出23,对应二进制 0000000000010111

可选调整项

  • 如果需要把数组第一个bool对应short的高位,可以在转换后对short值做位反转操作
  • 如果需要指定大端/小端字节序,可以在读取short后判断BitConverter.IsLittleEndian再做字节反转

内容的提问来源于stack exchange,提问作者djc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:18:02