C#中獲取byte第四位和高四位方法和獲取設置byte每一位的值


C#低四位

      public static int GetLow4(byte data)
        {//獲取低四位
            return data & 0x0f;
        }

C#高四位

        public static int getHeight4(byte data)
        {//獲取高四位
            return (data & 0xf0) >> 4;
        }

C#獲取每一位的值

        /// <summary>
        /// 獲取字節中的指定Bit的值
        /// </summary>
        /// <param name="this">字節</param>
        /// <param name="index">Bit的索引值(0-7)</param>
        /// <returns></returns>
        public static int GetBit(byte data, 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 (data & x) == x ? 1 : 0;
        }

C#中關於獲取查看二進制的方法,還有這么一種

byte b = 200;
string s = Convert.ToString(b, 2);

 

C#設置每一位的值(這個我其實看不懂,不知道對不對,有點渣)

        /// <summary>
        /// 設置某一位的值
        /// </summary>
        /// <param name="data">需要設置的byte數據</param>
        /// <param name="index">要設置的位, 值從低到高為 1-8</param>
        /// <param name="flag">要設置的值 true / false</param>
        /// <returns></returns>
        public static byte set_bit(byte data, int index, bool flag)
        {
            if (index > 8 || index < 1)
                throw new ArgumentOutOfRangeException("位過8或小於1是不可以的");
            int v = index < 2 ? index : (2 << (index - 2));
            return flag ? (byte)(data | v) : (byte)(data & ~v);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM