BitMapHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Edge.Core.Parser.BinaryParser.Util;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace ShellChina_EPS_Project_CarPlatePay_EpsClient_App.MessageEntity
  7. {
  8. public static class BitMapHelper
  9. {
  10. /// <summary>
  11. /// create 8 bytes map.
  12. /// </summary>
  13. /// <returns></returns>
  14. public static byte[] CreateMap()
  15. {
  16. byte[] map = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
  17. return map;
  18. }
  19. /// <summary>
  20. /// create 8 bytes map with fields enabled(correlated bit set to 1)
  21. /// </summary>
  22. /// <param name="enablingFieldIndexes">1 based, means the first field's index is 1</param>
  23. /// <returns></returns>
  24. public static byte[] CreateMap(params int[] enablingFieldIndexes)
  25. {
  26. if (enablingFieldIndexes.Any(i => i < 1)) throw new ArgumentOutOfRangeException("fields' index must >=1");
  27. byte[] map = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
  28. return map.Enable(enablingFieldIndexes);
  29. }
  30. public static byte[] Enable(this byte[] map, params int[] enablingFieldIndexes)
  31. {
  32. for (int i = 0; i < enablingFieldIndexes.Length; i++)
  33. {
  34. var fieldIndex = enablingFieldIndexes[i] - 1;
  35. var groupIndex = fieldIndex / 8;
  36. var groupInternalIndex = fieldIndex % 8;
  37. map[groupIndex] = map[groupIndex].SetBit(7 - groupInternalIndex, 7 - groupInternalIndex, 1);
  38. }
  39. return map;
  40. }
  41. public static byte[] Disable(this byte[] map, params int[] disablingFieldIndexes)
  42. {
  43. for (int i = 0; i < disablingFieldIndexes.Length; i++)
  44. {
  45. var fieldIndex = disablingFieldIndexes[i] - 1;
  46. var groupIndex = fieldIndex / 8;
  47. var groupInternalIndex = fieldIndex % 8;
  48. map[groupIndex] = map[groupIndex].SetBit(7 - groupInternalIndex, 7 - groupInternalIndex, 0);
  49. }
  50. return map;
  51. }
  52. /// <summary>
  53. /// check if target field presents in map
  54. /// </summary>
  55. /// <param name="map"></param>
  56. /// <param name="fieldIndex">0 based</param>
  57. /// <returns>true for present, otherwise, ommit</returns>
  58. public static bool Determine(this IList<byte> map, int fieldIndex)
  59. {
  60. var groupIndex = (fieldIndex - 1) / 8;
  61. var groupInternalIndex = (fieldIndex - 1) % 8;
  62. return map[groupIndex].GetBit(7 - groupInternalIndex) == 1;
  63. }
  64. public static List<int> Determine(this IList<byte> map)
  65. {
  66. var result = new List<int>();
  67. for (int i = 0; i < map.Count; i++)
  68. {
  69. for (int j = 7; j >= 0; j--)
  70. {
  71. if (map[i].GetBit(j) == 1)
  72. result.Add(i * 8 + 7 - j + 1);
  73. }
  74. }
  75. return result;
  76. }
  77. }
  78. }