How to convert System.Decimal bits to string in C#?

前端 未结 4 1796
天涯浪人
天涯浪人 2021-01-18 20:36

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.ToStri

4条回答
  •  温柔的废话
    2021-01-18 21:00

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

    • https://github.com/mono/mono/blob/master/mcs/class/corlib/System/NumberFormatter.cs

    The entry point is NumberToString(string, decimal, IFormatProvider).

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

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

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

提交回复
热议问题