二进制数组与基础类型转换

/// <summary>
/// 工具类:对象与二进制流间的转换
/// </summary>
class ByteConvertHelper
{
/// <summary>
/// 将对象转换为byte数组
/// </summary>
/// <param name="obj">被转换对象</param>
/// <returns>转换后byte数组</returns>
public static byte[] Object2Bytes(object obj)
{
byte[] buff = new byte[Marshal.SizeOf(obj)];
IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
Marshal.StructureToPtr(obj, ptr, true);
return buff;
}

/// <summary>
/// 将byte数组转换成对象
/// </summary>
/// <param name="buff">被转换byte数组</param>
/// <param name="typ">转换成的类名</param>
/// <returns>转换完成后的对象</returns>
public static object Bytes2Object(byte[] buff, Type typ)
{
IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(buff, 0);
return Marshal.PtrToStructure(ptr, typ);
}
}

posted @   孙延坤  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示