8

What is the smartest way to load a string like "10101011101010" directly into a new bit array? (not a byte array)

(The bits should remain in the same order as in the list.)

akjoshi
  • 14,989
  • 13
  • 101
  • 119
Pam
  • 444
  • 1
  • 4
  • 12

3 Answers3

11

You can do it with LINQ:

var res = new BitArray(str.Select(c => c == '1').ToArray());
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • This one so far works best (Soner came up with same idea). I am accepting this, but let me know about any new idea. Thank you dasblinkenlight. – Pam Dec 19 '12 at 11:39
3

You can use LINQ on this case like;

var yourbitarray = new BitArray(yourstring.Select(s => s == '1').ToArray());
Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
0

How about something like this:

string bits = "101010101010";
byte[] bytes = bits.ToCharArray().Select(c => (byte)c == '0' ? 0 : 1).ToArray();

Might work...

or

byte[] bytes = bits.Select(c => (byte)c == '0' ? 0 : 1).ToArray();
samjudson
  • 54,960
  • 7
  • 57
  • 68
  • 1
    Sorry. See one of the other excellent answers in that case (or pass the byte array into the constructor of the BitArray class). – samjudson Dec 19 '12 at 12:46