Load a (0/1) string into a bit array
Asked Answered
B

3

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.)

Beige answered 19/12, 2012 at 11:10 Comment(0)
H
12

You can do it with LINQ:

var res = new BitArray(str.Select(c => c == '1').ToArray());
Holohedral answered 19/12, 2012 at 11:12 Comment(1)
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.Beige
S
4

You can use LINQ on this case like;

var yourbitarray = new BitArray(yourstring.Select(s => s == '1').ToArray());
Shinn answered 19/12, 2012 at 11:15 Comment(0)
S
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();
Stroll answered 19/12, 2012 at 11:13 Comment(1)
Sorry. See one of the other excellent answers in that case (or pass the byte array into the constructor of the BitArray class).Stroll

© 2022 - 2024 — McMap. All rights reserved.