PMe
PMe

Reputation: 565

C# BitArray with leading zeros

I've tried something like this:

BitArray bits = new BitArray(00001110);

But the result is 1110

It seems like the BitArray cut the leading zeros.

Is it possible to create a BitArray with the leading zeros?

Upvotes: 1

Views: 1112

Answers (1)

adjan
adjan

Reputation: 13684

BitArray bits = new BitArray(00001110);

just sets the size of the BitArray to 1110. What you want is

bool[] array = new bool[] {false, false, false, false, true, true, true, false};
BitArray bits = new BitArray(array);

or using

BitArray bits = new BitArray(new byte[] {0x70});

which is rather unintuitive because the bits of the second digit are put first, and the bits of each digit are reversed in order.

Further, with C# 7.0 you can set the byte value using a binary literal as well:

BitArray bits = new BitArray(new byte[] {0b0111_0000});

Upvotes: 3

Related Questions