1

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?

PMe
  • 545
  • 2
  • 9
  • 20
  • What ouput format are you looking for - a BitArray would not have leading zeroes. Do you want to convert it to a string? – Brian Jun 14 '17 at 05:20
  • 1
    _"But the result is 1110"_ -- not with the code you posted, it's not. The only matching constructor would be the `BitArray(int)` overload, in which case the `00001110` would be taken literally as an `int` value specifying a `BitArray` object with one thousand, one hundred and ten bits in it, all initialized to zero. Please fix your question so it includes a good [mcve] that reliably reproduces your problem. – Peter Duniho Jun 14 '17 at 05:30
  • As of C# 7 you can use binary literals like, `new BitArray(0b0000_1110);` – Mike Zboray Jun 14 '17 at 06:23
  • @mikez this still just sets the size of the array (to 14). You have to pass a `byte[]` array instead. See my answer. – adjan Jun 14 '17 at 08:05
  • @adjan Oh quite right. I didn't look at the docs. – Mike Zboray Jun 14 '17 at 08:10

1 Answers1

3
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});
adjan
  • 13,371
  • 2
  • 31
  • 48