Files
YuPu-OrpaonEMS/OrpaonEMS.App/Com/BitHelper.cs
2025-02-28 22:23:13 +08:00

72 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrpaonEMS.App.Com
{
public class BitHelper
{
/// <summary>
/// 获取字的高字节
/// </summary>
public static byte GetHByteUint16(ushort data)
{
return (byte)(data >> 8);//高位
}
/// <summary>
/// 获取字的低字节
/// </summary>
public static byte GetLByteUint16(ushort data)
{
return (byte)(data & 0xff);//低位
}
/// <summary>
/// 根据Int类型的值返回用1或0(对应True或Flase)填充的数组
/// <remarks>从右侧开始向左索引(0~31)</remarks>
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static IEnumerable<bool> GetBitList(int value)
{
var list = new List<bool>(32);
for (var i = 0; i <= 31; i++)
{
var val = 1 << i;
list.Add((value & val) == val);
}
return list;
}
/// <summary>
/// 返回Int数据中某一位是否为1
/// </summary>
/// <param name="value"></param>
/// <param name="index">32位数据的从右向左的偏移位索引(0~31)</param>
/// <returns>true表示该位为1false表示该位为0</returns>
public static bool GetBitValue(int value, ushort index)
{
if (index > 31) throw new ArgumentOutOfRangeException("index"); //索引出错
var val = 1 << index;
return (value & val) == val;
}
/// <summary>
/// 设定Int数据中某一位的值
/// </summary>
/// <param name="value">位设定前的值</param>
/// <param name="index">32位数据的从右向左的偏移位索引(0~31)</param>
/// <param name="bitValue">true设该位为1,false设为0</param>
/// <returns>返回位设定后的值</returns>
public static int SetBitValue(int value, ushort index, bool bitValue)
{
if (index > 31) throw new ArgumentOutOfRangeException("index"); //索引出错
var val = 1 << index;
return bitValue ? (value | val) : (value & ~val);
}
}
}