Binary representation of a .NET Decimal

耗尽温柔 提交于 2019-12-17 19:17:57

问题


How does a .NET decimal type get represented in binary in memory?

We all know how floating-point numbers are stored and the thusly the reasons for the inaccuracy thereof, but I can't find any information about decimal except the following:

  1. Apparently more accurate than floating-point numbers
  2. Takes 128 bits of memory
  3. 2^96 + sign range
  4. 28 (sometimes 29?) total significant digits in the number

Is there any way I can figure this out? The computer scientist in me demands the answer and after an hour of attempted research, I cannot find it. It seems like there's either a lot of wasted bits or I'm just picturing this wrong in my head. Can anyone shed some light on this please?


回答1:


Decimal.GetBits for the information you want.

Basically it's a 96 bit integer as the mantissa, plus a sign bit, plus an exponent to say how many decimal places to shift it to the right.

So to represent 3.261 you'd have a mantissa of 3261, a sign bit of 0 (i.e. positive), and an exponent of 3. Note that decimal isn't normalized (deliberately) so you can also represent 3.2610 by using a mantissa of 32610 and an exponent of 4, for example.

I have some more information in my article on decimal floating point.




回答2:


https://www.csharpindepth.com/Articles/Decimal

How is a decimal stored?

A decimal is stored in 128 bits, even though only 102 are strictly necessary. It is convenient to consider the decimal as three 32-bit integers representing the mantissa, and then one integer representing the sign and exponent. The top bit of the last integer is the sign bit (in the normal way, with the bit being set (1) for negative numbers) and bits 16-23 (the low bits of the high 16-bit word) contain the exponent. The other bits must all be clear (0). This representation is the one given by decimal.GetBits(decimal) which returns an array of 4 ints.



来源:https://stackoverflow.com/questions/3801440/binary-representation-of-a-net-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!