Skip to content

Instantly share code, notes, and snippets.

@castaneai
Last active August 16, 2016 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save castaneai/ba08b1ccc1d089791011fb02df5cf2ae to your computer and use it in GitHub Desktop.
Save castaneai/ba08b1ccc1d089791011fb02df5cf2ae to your computer and use it in GitHub Desktop.
program 0817
using System;
using System.Collections;
using System.Linq;
class Program0817
{
static void Main(string[] args)
{
var data = new byte[]
{
0,0,0,1,1,1,0,0,
0,0,1,1,1,1,0,0,
0,0,0,1,0,1,0,0,
0,0,1,1,0,1,0,0,
0,0,0,1,1,1,0,1,
1,0,0,1,1,1,0,0,
};
Console.WriteLine("original data(size={0}): {1}", data.Length, string.Join(", ", data));
var enc = Serialize(data);
Console.WriteLine("serialized data(size={0}): {1}", enc.Length, string.Join(", ", enc));
var dec = Deserialize(enc);
Console.WriteLine("deserialized data(size={0}): {1}", dec.Length, string.Join(", ", dec));
}
static byte[] Serialize(byte[] data)
{
var result = new byte[1 + data.Length / 8 + data.Length % 8];
result[0] = (byte)data.Length;
new BitArray(data.Select(b => b == 1).ToArray()).CopyTo(result, 1);
return result;
}
static byte[] Deserialize(byte[] data)
{
var size = data[0];
var result = new bool[(size + 8 - 1) & ~(8 - 1)];
new BitArray(data.Skip(1).ToArray()).CopyTo(result, 0);
return result.Take(size).Select(b => b ? (byte)1 : (byte)0).ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment