如何在 C# 中将 System.Decimal 位转换为字符串?
我希望能够从 System.Decimal 值获取位,然后将其转换为该值的字符串表示形式,就像 Decimal.ToString() 一样可以,但我很难想出算法。
所以我有这样的事情:
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 个整数包含值位,最后一个整数包含符号位和比例因子。
我尝试使用各种搜索词来搜索算法,但十进制主要用作“浮点数”的同义词,因此我的搜索找到了不相关问题的答案。
任何帮助将不胜感激。
编辑:为了回应一些答案,我需要将这些位发送到需要重建值的不同平台。 System.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"?
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.
Any help would be appreciated.
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.
If I had a choice, I'd obviously use ToString()
but then I wouldn't need to ask.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 Decimal 构造函数 Decimal(Int32[]) 将您的值转换回来:
之后,如果需要,您可以使用
ToString
。例子:
You can use the Decimal constructor Decimal(Int32[]) to convert your value back:
Afterwards, you can use
ToString
if you want.Example:
这不是算法,但我想它应该有帮助。
小数位结构:
It's does not algoritm, but i suppose it should help.
Decimal bits structure:
有什么主要原因不能只使用十进制构造函数吗?
Is there any major reason you can't just use the decimal constructor?
由于您无法使用
ToString()
,您可能需要查看单声道开发人员如何实现此功能:该条目点是 NumberToString(string,decimal, IFormatProvider )。
有趣的部分是 InitDecHexDigits(uint, ulong ),它被这样调用
,并执行“位杂耍和移位”操作,将三个整数转换为 二进制编码的小数 (
_val1
到_val4
),然后可以(简单地)转换为字符串。(不要对他们称之为“十六进制表示”的事实感到困惑。它是二进制编码的十进制数字。)
Since you cannot use
ToString()
, you might want to check out how the mono developers implemented this:The entry point is NumberToString(string, decimal, IFormatProvider).
The interesting part is InitDecHexDigits(uint, ulong), which gets called like this
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.(Don't get confused by the fact that they call it "hex representation". It's binary coded decimal digits.)