BitArray.this

Creates a BitArray from the raw contents of the source array. The source array is not copied but simply acts as the underlying array of bits, which stores data as size_t units.

That means a particular care should be taken when passing an array of a type different than size_t, firstly because its length should be a multiple of size_t.sizeof, and secondly because how the bits are mapped:

size_t[] source = [1, 2, 3, 3424234, 724398, 230947, 389492];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
    auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
    assert(ba[n] == nth_bit);
}

The least significant bit in any size_t unit is the starting bit of this unit, and the most significant bit is the last bit of this unit. Therefore, passing e.g. an array of ints may result in a different BitArray depending on the processor's endianness.

This constructor is the inverse of opCast.

  1. this(bool[] ba)
  2. this(void[] v, size_t numbits)
    struct BitArray
    @nogc nothrow pure
    this
    (
    void[] v
    ,
    size_t numbits
    )

Parameters

v void[]

Source array. v.length must be a multple of size_t.sizeof.

numbits size_t

Number of bits to be mapped from the source array, i.e. length of the created BitArray.

Examples

import std.algorithm.comparison : equal;

auto a = BitArray([1, 0, 0, 1, 1]);

// Inverse of the cast.
auto v = cast(void[]) a;
auto b = BitArray(v, a.length);

assert(b.length == 5);
assert(b.bitsSet.equal([0, 3, 4]));

// a and b share the underlying data.
a[0] = 0;
assert(b[0] == 0);
assert(a == b);
import std.algorithm.comparison : equal;

size_t[] source = [0b1100, 0b0011];
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
// The least significant bit in each unit is this unit's starting bit.
assert(ba.bitsSet.equal([2, 3, sbits, sbits + 1]));
// Example from the doc for this constructor.
static immutable size_t[] sourceData = [1, 0b101, 3, 3424234, 724398, 230947, 389492];
size_t[] source = sourceData.dup;
enum sbits = size_t.sizeof * 8;
auto ba = BitArray(source, source.length * sbits);
foreach (n; 0 .. source.length * sbits)
{
    auto nth_bit = cast(bool) (source[n / sbits] & (1L << (n % sbits)));
    assert(ba[n] == nth_bit);
}

// Example of mapping only part of the array.
import std.algorithm.comparison : equal;

auto bc = BitArray(source, sbits + 1);
assert(bc.bitsSet.equal([0, sbits]));
// Source array has not been modified.
assert(source == sourceData);

Meta