Load a (0/1) string into a bit array

后端 未结 3 1135
南旧
南旧 2021-01-12 04:58

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

(The bits shoul

相关标签:
3条回答
  • 2021-01-12 05:26

    You can do it with LINQ:

    var res = new BitArray(str.Select(c => c == '1').ToArray());
    
    0 讨论(0)
  • 2021-01-12 05:34

    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();
    
    0 讨论(0)
  • 2021-01-12 05:47

    You can use LINQ on this case like;

    var yourbitarray = new BitArray(yourstring.Select(s => s == '1').ToArray());
    
    0 讨论(0)
提交回复
热议问题