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); }