Skip to content

Instantly share code, notes, and snippets.

@Cologler
Created July 19, 2022 13:42
Show Gist options
  • Save Cologler/84b2775831fb79fece5056da8d4299f8 to your computer and use it in GitHub Desktop.
Save Cologler/84b2775831fb79fece5056da8d4299f8 to your computer and use it in GitHub Desktop.
BitArray to array
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;
}
}
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