c#中decimal类型的二进制序列化和反序列化

Binary serialization and deserialization of decimal type in c#

为了对十进制类型进行二进制序列化,我执行以下操作:

var ms = new MemoryStream();
decimal d = 123.45M;
int[] bits = Decimal.GetBits(d);
for(int i=0; i<4; i++)
    ms.Write(BitConverter.GetBytes(bits[i]),0,4);

现在我有了一个 int[] bits 变量,我怎样才能将它转换回小数?或者如何将内存流中的 16 个字节转换回十进制?这可以在不必使用不安全代码的情况下完成吗?

用float、int、bool等类型简单搞定。我只使用 System.Convert 和 BitConverter static 类.

抱歉发布问题,我本应该尝试更长时间。我很困惑,因为所有其他类型都使用了 System.Convert 和 BitConverter.

无论如何只需要这样做:

decimal originalDecimal = 123.45M;
int[] bits = Decimal.GetBits(originalDecimal);
decimal cloneDecimal = new Decimal(bits);