瀏覽代碼

1、增加byte数组和数据相互转换方法

法 王 1 周之前
父節點
當前提交
5848ffa219
共有 1 個文件被更改,包括 61 次插入0 次删除
  1. 61 0
      SKMC.API/Common/CommonUtil.cs

+ 61 - 0
SKMC.API/Common/CommonUtil.cs

@@ -112,6 +112,67 @@ namespace SKMC.Api.Common
             }
         }
 
+        /// <summary>
+        /// 自动根据字节长度,返回对应有符号数值类型
+        /// </summary>
+        public static object AutoConvertToValue(byte[] bytes)
+        {
+            if (bytes == null || bytes.Length == 0)
+                return 0;
+
+            switch(bytes.Length)
+            {
+                case 2:
+                    return BitConverter.ToInt16(bytes, 0);
+                case 4:
+                    return BitConverter.ToInt32(bytes, 0);
+                case 8:
+                    return BitConverter.ToInt64(bytes, 0);
+                default:
+                    return BitConverter.ToInt64(bytes, 0);
+            }
+        }
+
+        /// <summary>
+        /// 自动根据字节长度,返回对应无符号数值类型
+        /// </summary>
+        public static object AutoConvertToUnsignedValue(byte[] bytes)
+        {
+            if (bytes == null || bytes.Length == 0)
+                return 0;
+
+            switch (bytes.Length)
+            {
+                case 2:
+                    return BitConverter.ToUInt16(bytes, 0);
+                case 4:
+                    return BitConverter.ToUInt32(bytes, 0);
+                case 8:
+                    return BitConverter.ToUInt64(bytes, 0);
+                default:
+                    return BitConverter.ToUInt64(bytes, 0);
+            }
+        }
+
+        /// <summary>
+        /// 将 long 转为 固定长度的字节数组(小端)
+        /// 支持:1、2、4、8 字节
+        /// 不足自动补0,超长自动截断
+        /// </summary>
+        public static byte[] ToFixedBytes(long value, int fixedLength)
+        {
+            // 支持 1/2/4/8 字节
+            // 先转成标准8字节
+            byte[] bytes = BitConverter.GetBytes(value);
+            byte[] result = new byte[fixedLength];
+
+            // 取前面fixedLength 字节
+            int copyLen = Math.Min(bytes.Length, fixedLength);
+            Array.Copy(bytes, result, copyLen);
+
+            return result;
+        }
+
         /// <summary>
         /// Float类型変換
         /// </summary>