Skip to content

Instantly share code, notes, and snippets.

@NNNIC
Created July 17, 2019 06:15
Show Gist options
  • Save NNNIC/14c93b47fddfb168cfbfa62fc75acbe0 to your computer and use it in GitHub Desktop.
Save NNNIC/14c93b47fddfb168cfbfa62fc75acbe0 to your computer and use it in GitHub Desktop.
bitconverter sample C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class item {
public bool p;
public bool v;
};
class Program
{
static Random rand = null;
static bool randbool() {
if (rand==null) rand = new Random((int)System.DateTime.Now.ToBinary());
var i = rand.Next();
return (i%2==0);
}
static void Main(string[] args)
{
Dictionary<int, item> dic = new Dictionary<int, item>();
for(var i = 1; i<100; i++)
{
dic.Add(i, new item() { p = randbool(), v=randbool() });
}
var s = compress(dic);
Console.WriteLine(s);
var tmpdic = decompress(s);
var tmps = compress(tmpdic);
Console.WriteLine(tmps);
if (dic.Count != tmpdic.Count)
Console.WriteLine("Unexpeced!");
foreach(var k in dic.Keys)
{
var v = dic[k];
var t = tmpdic[k];
if (
v.p != t.p
||
v.v != t.v
)
{
Console.WriteLine("Unexpected");
}
}
Console.WriteLine("END");
}
static string compress(Dictionary<int, item> dic)
{
//最大・最小
var min = int.MaxValue;
var max = int.MinValue;
foreach(var k in dic.Keys)
{
if (k > max) max = k;
if (k < min) min = k;
}
var bitarray = new BitArray(dic.Count * 2);
for(var i = min; i <= max; i++)
{
bitarray.Set((i - min) * 2 + 0, dic[i].p);
bitarray.Set((i - min) * 2 + 1, dic[i].v);
}
var bytearray = new byte[ (int) Math.Ceiling( (double)dic.Count * 2 / 8 ) ];
bitarray.CopyTo(bytearray,0);
var s = string.Empty;
Array.ForEach(bytearray, i=>{
if (!string.IsNullOrEmpty(s)) s+= ",";
s+= i.ToString();
});
return min.ToString() + "," +max.ToString() + "," + s;
}
static Dictionary<int, item> decompress(string text)
{
var tok = text.Split(',');
var list = new List<int>();
foreach(var t in tok)
{
var n = int.Parse(t);
list.Add(n);
}
var min = list[0];
var max = list[1];
var byte_list = new List<byte>();
for(var i = 2; i<list.Count; i++)
{
byte_list.Add((byte)list[i]);
}
var bitarray = new BitArray(byte_list.ToArray());
var dic = new Dictionary<int, item>();
for (var i = min; i<=max; i++)
{
var item = new item();
item.p = bitarray.Get((i-min) * 2 + 0);
item.v = bitarray.Get((i-min) * 2 + 1);
dic.Add(i,item);
}
return dic;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment