C#泛型函数实现:将数值类型转为反转字节数组
嘿,我来帮你搞定这个泛型字节反转函数!之前用BinaryFormatter走不通是因为它序列化时会带上额外的类型元数据,根本不是你要的原始数值字节,咱们换个更直接的思路——用BitConverter来处理基本数值类型的字节转换,再反转数组就搞定了。
下面是实现好的泛型函数,完美支持你要的int、short、Single、Double类型:
public static byte[] ReverseBytes<T>(T value) where T : struct { byte[] bytes; // 根据泛型类型选择对应的BitConverter方法 switch (Type.GetTypeCode(typeof(T))) { case TypeCode.Int32: bytes = BitConverter.GetBytes(Convert.ToInt32(value)); break; case TypeCode.Int16: bytes = BitConverter.GetBytes(Convert.ToInt16(value)); break; case TypeCode.Single: bytes = BitConverter.GetBytes(Convert.ToSingle(value)); break; case TypeCode.Double: bytes = BitConverter.GetBytes(Convert.ToDouble(value)); break; default: throw new ArgumentException($"不支持的类型:{typeof(T)}", nameof(value)); } // 反转字节数组 Array.Reverse(bytes); return bytes; }
为什么这么写?
- 类型约束:用
where T : struct确保只能传入值类型,避免无效的引用类型参数。 - 类型分支处理:因为
BitConverter没有泛型版本,所以通过TypeCode判断具体类型,调用对应的GetBytes方法,直接获取数值的原始字节。 - 反转数组:用
Array.Reverse一键反转字节顺序,正好匹配你要的示例结果。
测试你的示例:
- 传入
2.0f:ReverseBytes(2.0f)会返回[0x40, 0x00, 0x00, 0x00],和你要的结果一致。 - 传入
0x01020304(int):反转后得到[0x01, 0x02, 0x03, 0x04],完全符合预期。 - 传入
(short)0x0102:返回[0x01, 0x02],没问题。
如果你想更严格的类型检查,还可以在函数开头额外判断类型是否在允许的列表里,不过上面的switch已经覆盖了你的需求啦。
内容的提问来源于stack exchange,提问作者elections 12
相关产品推荐
相关产品推荐

