分支自 SuZhouGuanHong/TaiYuanTaiZhong

huanghongfeng
2024-07-15 a765da90e5ee63e04d2d8460a5ad1ebd0e8eb4db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace WIDESEA_Comm.DataHandle
{
    public class DataParse
    {
        /// <summary>
        /// 字节转bit字符串(注意偏移量0,对应的是下标0)
        /// </summary>
        /// <param name="b">字节</param>
        /// <returns></returns>
        public static char[] Byte2Bit(byte b)
        {
            var strTemp = Convert.ToString(b, 2).PadLeft(8, '0').ToCharArray();
            Array.Reverse(strTemp);
            return strTemp;
        }
 
        /// <summary>
        /// 获取字符串【西门子】
        /// </summary>
        /// <param name="socure">源</param>
        /// <param name="start">起始位置</param>
        /// <returns></returns>
        public static string GetStr(byte[] socure, int start)
        {
            //有效长度
            int truelength = socure[start + 1];
            //前两位是西门标识位
            if (truelength > socure.Length - 2)
            {
                truelength = socure.Length - 2;
            }
            List<byte> newByte = new List<byte>();
            for (int i = 0; i < truelength; i++)
            {
                newByte.Add(socure[start + i + 2]);
            }
            return Encoding.ASCII.GetString(newByte.ToArray()).Replace("\0", "");
        }
 
        /// <summary>
        /// 8比特位转字节
        /// </summary>
        /// <param name="bitStr">第一个权重最低</param>
        /// <returns></returns>
        public static byte Bit2Byte(char[] chardatas)
        {
            if (chardatas.Length != 8)
            {
                throw new Exception("请输入8位的bit字符串");
            }
 
            int res = 0;
            for (int i = 0; i < 8; i++)
            {
                var value = short.Parse(chardatas[i].ToString()) * Math.Pow(2, i);
                res += (int)value;
            }
            if (res > 255)
            {
                throw new Exception("bit超出字节大小255");
            }
            return (byte)res;
        }
    }
}