|
发表于 2017-7-7 20:58:21
|
显示全部楼层
给你几个用for循环实现的,效率差点,还是能用的,需要效率的话你自己写吧
- /// <summary>
- /// Intel
- /// </summary>
- /// <param name="bytes"></param>
- /// <param name="start"></param>
- /// <param name="length"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static byte[] SetBitIntel(this byte[] bytes, int start, int length, uint value)
- {
- for (int i = 0; i < length; i++)
- {
- int posByte = (i+ start) / 8;
- int posBit = (i + start) % 8;
- byte bitValue = (byte)((value >> i) & 0x01);
- bytes[posByte] &= (byte)(~(1 << posBit));
- bytes[posByte] |= (byte)(bitValue<< posBit);
- }
- return bytes;
- }
- /// <summary>
- /// Intel
- /// </summary>
- /// <param name="bytes"></param>
- /// <param name="start"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static uint GetBitIntel(this byte[] bytes, int start, int length)
- {
- uint value = 0;
- for (int i = 0; i < length; i++)
- {
- int posByte = (i + start) / 8;
- int posBit = (i + start) % 8;
- value |= (((uint)bytes[posByte] >> posBit) & 0x01) << i;
- }
- return value;
- }
- /// <summary>
- /// Motorola
- /// </summary>
- /// <param name="bytes"></param>
- /// <param name="start"></param>
- /// <param name="length"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static byte[] SetBitMotorola(this byte[] bytes, int start, int length, uint value)
- {
- int posByte = start / 8;
- int posBit = start % 8;
- for (int i = 0; i < length; i++)
- {
- byte bitValue = (byte)((value >> i) & 0x01);
- bytes[posByte] &= (byte)(~(1 << posBit));
- bytes[posByte] |= (byte)(bitValue << posBit);
- if(i >= length)
- {
- break;
- }
- if(++posBit >= 8)
- {
- posBit = 0;
- posByte--;
- }
- }
- return bytes;
- }
- /// <summary>
- /// Motorola
- /// </summary>
- /// <param name="bytes"></param>
- /// <param name="start"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public static uint GetBitMotorola(this byte[] bytes, int start, int length)
- {
- uint value = 0;
- int posByte = start / 8;
- int posBit = start % 8;
- for (int i = 0; i < length; i++)
- {
- value |= (((uint)bytes[posByte] >> posBit) & 0x01) << i;
- if (i >= length)
- {
- break;
- }
- if (++posBit >= 8)
- {
- posBit = 0;
- posByte--;
- }
- }
- return value;
- }
复制代码 |
|