Dispenser/DispenserCommon/Utils/ValueUtil.cs

42 lines
1.4 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.

namespace DispenserCommon.Utils;
public static class ValueUtil
{
/// <summary>
/// 将 int 转为 8 bit 的二进制字符串,前面不足的补 0
/// </summary>
public static string Int2BitStr(int val, int bitLen)
{
return new string(Int2BitChars(val, bitLen));
}
/// <summary>
/// </summary>
/// <param name="val"></param>
/// <param name="bitLen"></param>
/// <returns></returns>
public static char[] Int2BitChars(int val, int bitLen)
{
// 直接将整数val转换为二进制字符串不考虑十六进制。
var binaryString = Convert.ToString(val, 2);
// 如果val为负数binaryString将包含二进制补码形式的字符串其长度可能超过bitLen。
// 根据需要裁剪或填充字符串以适应指定的位长度(bitLen)。
if (binaryString.Length > bitLen)
// 对于负数,去除多余的前导'1'。
binaryString = binaryString.Substring(binaryString.Length - bitLen);
else
// 填充以达到所需长度。
binaryString = binaryString.PadLeft(bitLen, '0');
// 反转和转换为字符数组。
var chars = binaryString.Reverse().ToArray();
return chars;
}
public static int BitChars2Int(char[] chars)
{
return Convert.ToInt32(new string(chars), 2);
}
}