123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- namespace Vinno.FIS.Sonopost.Features.Oled
- {
- public static class MessageVerify
- {
- /// <summary>
- /// 偶校验算法获得校验码
- /// </summary>
- /// <param name="date"></param>
- /// <returns></returns>
- public static byte[] EvenCode(byte[] data)
- {
- byte[] bVerify = new byte[data.Length / 8 + 2];//校验位接收数组
- bVerify[bVerify.Length - 1] = (byte)bVerify.Length;//校验位长度
- //计算校验位数据
- for (int i = 0; i < data.Length; i++)//每个位去处理
- {
- if (GetOddEvenVerify(data[i]))
- {//奇数 //1;
- set_bit(ref bVerify[i / 8], i);
- }
- else
- {//偶数//0;
- clr_bit(ref bVerify[i / 8], i);
- }
- }
- return bVerify;
- }
- /// <summary>
- /// 判断当前位1的个数是奇数个还是偶数个
- /// </summary>
- /// <param name="bData"></param>
- /// <returns>True 为奇数个 False 为偶数个</returns>
- private static bool GetOddEvenVerify(byte bData)
- {
- byte bcCount = 0; /* 字节内1的个数 */
- for (int i = 0; i < 8; i++)
- {
- if ((bData & (byte)0x01) == 1)
- {
- bcCount++;
- }
- bData >>= 1;
- }
- return ((bcCount & (byte)0x01) == 1);
- }
- /// <summary>
- /// 置位x的y位
- /// </summary>
- /// <param name="x"></param>
- /// <param name="y"></param>
- private static void set_bit(ref byte x, int y)
- {
- x = (byte)(x | (0x01 << (y)));
- }
- /// <summary>
- /// 清零x的y位
- /// </summary>
- /// <param name="x"></param>
- /// <param name="y"></param>
- private static void clr_bit(ref byte x, int y)
- {
- x = (byte)(x & ~(0x01 << (y)));
- }
- public static void Check(byte[] data, ref byte result, int len)
- {
- byte noBit = 0, num = 0, tem_re = 0, tem_s = 0;
- int index = 0;
- while (len-- > 0)
- {
- tem_s = data[index];
- while (tem_s > 0)
- {
- tem_s = (byte)(tem_s & (tem_s - 1));
- num++;
- }
- if ((num & 0x01) > 0)
- {
- set_bit(ref tem_re, noBit);
- }
- noBit++;
- if (noBit > 7)
- {
- noBit = 0;
- result++;
- result = tem_re;
- tem_re = 0;
- }
- index++;
- num = 0;
- }
- }
- }
- }
|