如何System.Decimal位转换为字符串在C#中? [英] How to convert System.Decimal bits to string in C#?

查看:422
本文介绍了如何System.Decimal位转换为字符串在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从 System.Decimal 价值得到位,然后将其转换为字符串重新的价值presentation,多如 Decimal.ToString的()会做,但我有一个很难想出的算法。

I'd like to be able to get the bits from a System.Decimal value and then convert that to the string representation of the value, much like Decimal.ToString() would do but I have a hard time coming up with the algorithm.

所以,我有这样的事情:

So I have something like this:

decimal d = 1403.45433M;
int[] nDecimalBits = decimal.GetBits(d);

// How to convert the 4 integers in nDecimalBits to a string
// that contains "1403.45433"?

我知道小数的二进制布局 - 前3个整数包含值位和最后一个整数包含符号位,比例因子

I know the binary layout of the decimal - the first 3 integers contain the value bits and the last integer contains the sign bit and the scaling factor.

我尝试使用不同的搜索条件,但小数搜索算法主要是用来作为同义词为浮点数所以我的搜索止跌回升答案无关的问题。

I tried searching for the algorithm using various search terms but decimal is mostly used as a synonym for 'floating-point number' so my searches turned up answers to unrelated problems.

任何帮助将是AP preciated。

Any help would be appreciated.

修改:针对一些答案,我需要派位到不同的平台,该值需要重建。 System.Decimal及其任何成员函数不可有,所以我要抢位,并将其转换为字符串。

Edit: in response to some answers, I need to send the bits to a different platform where the value needs to be reconstructed. System.Decimal and any of its member functions are not available there, so I need to grab the bits and translate them to a string.

如果我有一个选择,我明明用的ToString()但我并不需要问。

If I had a choice, I'd obviously use ToString() but then I wouldn't need to ask.

推荐答案

既然你不能使用的ToString(),你可能想看看如何单开发人员实现这

Since you cannot use ToString(), you might want to check out how the mono developers implemented this:

该入口点是 NumberToString(字符串,小数的IFormatProvider)

有趣的是 InitDecHexDigits( UINT,ULONG),这被称为像这样

The interesting part is InitDecHexDigits(uint, ulong), which gets called like this

InitDecHexDigits ((uint)bits [2], ((ulong)bits [1] << 32) | (uint)bits [0]);

和做的杂耍位和移位的东西三个整数转换成二进制codeD小数(的 _val1 _val4 ),然后可以(平凡)转换为字符串。

and does the "bit juggling and shifting" thing to convert the three integers into binary coded decimals (_val1 to _val4), which can then be (trivially) converted into a string.

(不要被他们称之为六角重新presentation的事实混淆。这是二进制codeD的十进制的数字。)

(Don't get confused by the fact that they call it "hex representation". It's binary coded decimal digits.)

这篇关于如何System.Decimal位转换为字符串在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆