How can I convert BitArray to single int?

后端 未结 4 916
借酒劲吻你
借酒劲吻你 2020-11-27 05:07

How can I convert BitArray to a single int?

4条回答
  •  伪装坚强ぢ
    2020-11-27 05:26

    This version:

    • works for up to 64 bits
    • doesn't rely on knowledge of BitArray implementation details
    • doesn't needlessly allocate memory
    • doesn't throw any exceptions (feel free to add a check if you expect more bits)
    • should be more than reasonably performant

    Implementation:

    public static ulong BitArrayToU64(BitArray ba)
    {
        var len = Math.Min(64, ba.Count);
        ulong n = 0;
        for (int i = 0; i < len; i++) {
            if (ba.Get(i))
                n |= 1UL << i;
        }
        return n;
    }
    

提交回复
热议问题