[英]Binary serialization and deserialization of decimal type in c#
In order to binary serialize a decimal type I do the following:为了对十进制类型进行二进制序列化,我执行以下操作:
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);
Now that I have a int[] bits
variable how can I convert that back to a decimal?现在我有一个
int[] bits
变量,我如何将它转换回十进制? Or how can I convert the 16 bytes in the memory stream back to a decimal?或者如何将 memory stream 中的 16 个字节转换回十进制? Is this possible to do without having to use unsafe code?
这可以在不必使用不安全代码的情况下完成吗?
With float, int, bool and other types that is simple to do.有了float、int、bool等类型就很简单了。 I just use the System.Convert and BitConverter static classes.
我只使用 System.Convert 和 BitConverter static 类。
Sorry for posting the question I should have had tried longer.很抱歉发布我应该尝试更长时间的问题。 I was confused because all the other types made use of System.Convert and BitConverter.
我很困惑,因为所有其他类型都使用了 System.Convert 和 BitConverter。
Anyways just have to do this:无论如何只需要这样做:
decimal originalDecimal = 123.45M;
int[] bits = Decimal.GetBits(originalDecimal);
decimal cloneDecimal = new Decimal(bits);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.