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.
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 (
_val1to_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.)