BitArray为整数问题

Grr*_*404 1 c# bitarray

public static int getIntegerFromBitArray(BitArray bitArray)
{
  var result = new int[1];
  bitArray.CopyTo(result, 0);
  return result[0];
}

// Input  A) 01110
// Output A) 14
// Input  B) 0011
// Output B) 12 <=== ????? WHY!!! :)
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么我的第二个返回值是12而不是3?求求你了,谢谢你.

Jon*_*eet 10

基本上它正在考虑与您期望的方式相反的位 - 您没有展示如何将输入二进制映射到a BitArray,但结果是将其视为1100而不是0011.

诚然,文档并不清楚,但它确实按照期望的方式工作:bitArray[0]代表不重要的值,就像讨论二进制时一样(因此位0是0/1,位1是0/2,位2是0/4,位3是0/8等.例如:

using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        BitArray bits = new BitArray(8);
        bits[0] = false;
        bits[1] = true;

        int[] array = new int[1];
        bits.CopyTo(array, 0);
        Console.WriteLine(array[0]); // Prints 2
    }
}
Run Code Online (Sandbox Code Playgroud)