Last active
August 16, 2016 18:07
-
-
Save castaneai/ba08b1ccc1d089791011fb02df5cf2ae to your computer and use it in GitHub Desktop.
program 0817
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; | |
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