using Edge.Core.Parser.BinaryParser.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShellChina_EPS_Project_CarPlatePay_EpsClient_App.MessageEntity
{
public static class BitMapHelper
{
///
/// create 8 bytes map.
///
///
public static byte[] CreateMap()
{
byte[] map = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
return map;
}
///
/// create 8 bytes map with fields enabled(correlated bit set to 1)
///
/// 1 based, means the first field's index is 1
///
public static byte[] CreateMap(params int[] enablingFieldIndexes)
{
if (enablingFieldIndexes.Any(i => i < 1)) throw new ArgumentOutOfRangeException("fields' index must >=1");
byte[] map = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
return map.Enable(enablingFieldIndexes);
}
public static byte[] Enable(this byte[] map, params int[] enablingFieldIndexes)
{
for (int i = 0; i < enablingFieldIndexes.Length; i++)
{
var fieldIndex = enablingFieldIndexes[i] - 1;
var groupIndex = fieldIndex / 8;
var groupInternalIndex = fieldIndex % 8;
map[groupIndex] = map[groupIndex].SetBit(7 - groupInternalIndex, 7 - groupInternalIndex, 1);
}
return map;
}
public static byte[] Disable(this byte[] map, params int[] disablingFieldIndexes)
{
for (int i = 0; i < disablingFieldIndexes.Length; i++)
{
var fieldIndex = disablingFieldIndexes[i] - 1;
var groupIndex = fieldIndex / 8;
var groupInternalIndex = fieldIndex % 8;
map[groupIndex] = map[groupIndex].SetBit(7 - groupInternalIndex, 7 - groupInternalIndex, 0);
}
return map;
}
///
/// check if target field presents in map
///
///
/// 0 based
/// true for present, otherwise, ommit
public static bool Determine(this IList map, int fieldIndex)
{
var groupIndex = (fieldIndex - 1) / 8;
var groupInternalIndex = (fieldIndex - 1) % 8;
return map[groupIndex].GetBit(7 - groupInternalIndex) == 1;
}
public static List Determine(this IList map)
{
var result = new List();
for (int i = 0; i < map.Count; i++)
{
for (int j = 7; j >= 0; j--)
{
if (map[i].GetBit(j) == 1)
result.Add(i * 8 + 7 - j + 1);
}
}
return result;
}
}
}