using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MWS.Library.Common
{
    public static class TranByte
    {
        /// <summary>
        /// 将byte转为对应的0/1数组,7对应低位
        /// </summary>
        /// <param name="bt"></param>
        /// <returns></returns>
        public static byte[] byteToArray(byte bt)
        {
            byte[] array = new byte[8];//用于存储每位的值
            for (int i = 7; i >= 0; i--)
            {
                array[i] = (byte)(bt & 1);//强转
                bt = (byte)(bt >> 1);//右移1位

            }
            return array;
        }
        /// <summary>
        /// 获取byte后三位转为int
        /// </summary>
        /// <param name="byt"></param>
        /// <returns></returns>
        public static int GetValue(byte byt)
        {
            int v0 = (byt & 0x01);
            int v1 = (byt & 0x02);
            int v2 = (byt & 0x04);
            return v0 + v1 + v2;

        }
        /// <summary>
        /// 将一个byte按高低字节返回
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static int[] SeparatingHighAndLowBits(byte b)
        {
            int[] HL = new int[2];//一个2位的数组，用于存获取到的高低位值
            var high = (b & 0xF0) >> 4;//高位
            var low = b & 0x0F;//低位
            HL[0] = high;
            HL[1] = low;
            return HL;//返回数组
        }
        /// <summary>
        /// 获取字节中的指定Bit的值
        /// </summary>
        /// <param name="byt">字节</param>
        /// <param name="index">Bit的索引值(0-7)</param>
        /// <returns></returns>
        public static int GetBit(byte byt, short index)
        {
            byte x = 1;
            switch (index)
            {
                case 0: { x = 0x01; } break;
                case 1: { x = 0x02; } break;
                case 2: { x = 0x04; } break;
                case 3: { x = 0x08; } break;
                case 4: { x = 0x10; } break;
                case 5: { x = 0x20; } break;
                case 6: { x = 0x40; } break;
                case 7: { x = 0x80; } break;
                default: { return 0; }
            }
            return (byt & x) == x ? 1 : 0;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static byte JudgeTempPositiveOrNegative(byte b)
        {
            //&是按位与之后的结果，所以最后要和本身【0x80】做比较
            if ((b & 0x80) == 0x80)//如果温度最高位是1，即为负数情况
            {
                Console.WriteLine("最高位为1");
                b = (byte)(b & 0x7F);//将b的最高位变为0，其他位不变
                Console.Write("最高位已改为0");
                return b;
            }
            else //如果温度最高位是0，为正数，则什么也不做
            {
                Console.Write("最高位为0");
                return b;
            }
        }

    }
}
