Created
July 19, 2022 13:42
-
-
Save Cologler/84b2775831fb79fece5056da8d4299f8 to your computer and use it in GitHub Desktop.
BitArray to array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class BitArrayExtensions | |
{ | |
public static byte[] ToByteArray(this BitArray bits) | |
{ | |
// copied from https://stackoverflow.com/questions/560123/convert-from-bitarray-to-byte | |
byte[] ret = new byte[(bits.Length + 7) >> 3]; | |
bits.CopyTo(ret, 0); | |
return ret; | |
} | |
public static int[] ToInt32Array(this BitArray bits) | |
{ | |
// copied from https://stackoverflow.com/questions/560123/convert-from-bitarray-to-byte | |
int[] ret = new int[(bits.Length + 31) >> 5]; | |
bits.CopyTo(ret, 0); | |
return ret; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Diagnostics; | |
foreach (var bytesCount in Enumerable.Range(0, 200)) | |
{ | |
var bb = GenerateBytes(bytesCount); | |
Debug.Assert(new BitArray(bb).ToByteArray().SequenceEqual(bb)); | |
var ib = GenerateInts(bytesCount); | |
Debug.Assert(new BitArray(ib).ToInt32Array().SequenceEqual(ib)); | |
} | |
Console.WriteLine("Completed."); | |
Console.ReadKey(); | |
static byte[] GenerateBytes(int count) | |
{ | |
var buf = new byte[count]; | |
new Random().NextBytes(buf); | |
return buf; | |
} | |
static int[] GenerateInts(int count) | |
{ | |
var rnd = new Random(); | |
var buf = new int[count]; | |
for (var i = 0; i < count; i++) | |
{ | |
buf[i] = rnd.Next(); | |
} | |
return buf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment