Skip to content

Instantly share code, notes, and snippets.

@cdiggins
Created August 24, 2019 04:01
Show Gist options
  • Save cdiggins/357203bb262488a319e7aacd97cd7234 to your computer and use it in GitHub Desktop.
Save cdiggins/357203bb262488a319e7aacd97cd7234 to your computer and use it in GitHub Desktop.
A simple algorithm for packing and unpacking binary byte arrays.
public static byte[] NaivePack(IList<byte[]> buffers)
{
using (var stream = new MemoryStream())
using (var bw = new BinaryWriter(stream))
{
bw.Write(buffers.Count);
foreach (var b in buffers)
{
bw.Write(b.Length);
bw.Write(b);
}
return stream.ToArray();
}
}
public static IList<byte[]> NaiveUnpack(byte[] data)
{
var r = new List<byte[]>();
using (var stream = new MemoryStream())
using (var br = new BinaryReader(stream))
{
var n = br.ReadInt32();
for (var i = 0; i < n; ++i)
{
var localN = br.ReadInt32();
var bytes = br.ReadBytes(localN);
r.Add(bytes);
}
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment