Binary Representation of "decimal"

This section describes binary representations of 'decimal' floating-point values according to the Microsoft .NET Framework reference manual.

The binary representation of a "decimal" value is well described by the description of the Decimal.GetBits() method in the Microsoft .NET Framework Reference manual.

The binary representation of a "decimal" value requires 128 bits with the following layout:

• 1 bit (bit 127) is used for the sign (s) as a integer.
• 7 bits (bits 126 to 120) are not used.
• 8 bits (bits 119 to 112) are used for the exponent (e) as a integer.
• 16 bits (bits 111 to 96) are not used.
• 96 bits (bits 95 to 0) are used for the coefficient (c) as a integer.

The value is then represented through the following expression:

```   v = (-1)^s * c * 10^(-e)
```

The following sample program illustrates the binary representation of several "decimal" values:

```// DecimalBits.cs

using System;
public class DecimalBits {
public static void Main() {
Console.WriteLine("s c        e                          v");
WriteBits(1.0m);
WriteBits(256.0m*256*256*128);
WriteBits(256.0m*256*256*256-1);
WriteBits(256.0m*256*256*256);
WriteBits(0.1m);
WriteBits(0.01m);
WriteBits(100.0m);
WriteBits(-1.0m);
WriteBits(1.0m/3);
WriteBits(2.0m/3);
}
public static void WriteBits(decimal value) {
int[] bits;
bits = decimal.GetBits(value);
Console.Write("{0}",((bits>>31)&0x1).ToString("X1"));
Console.Write(" __{0}____",
((bits&0x00ff0000)>>16).ToString("X2"));
Console.Write(" ");
for (int i=1; i<4; i++) {
Console.Write("{0} ",bits[3-i].ToString("X8"));
}
Console.WriteLine("{0}",value);
}
}
```

Output:

```s c        e                          v
0 __00____ 00000000 00000000 00000001 1
0 __00____ 00000000 00000000 80000000 2147483648
0 __00____ 00000000 00000000 FFFFFFFF 4294967295
0 __00____ 00000000 00000001 00000000 4294967296
0 __01____ 00000000 00000000 00000001 0.1
0 __02____ 00000000 00000000 00000001 0.01
0 __00____ 00000000 00000000 00000064 100
1 __00____ 00000000 00000000 00000001 -1
0 __1C____ 0AC544CA 14B700CB 05555555 0.3333333333333333333333333333
0 __1C____ 158A8994 296E0196 0AAAAAAB 0.6666666666666666666666666667
```

Comparing to the binary representation of "double", "decimal" has the advantage of capturing 4 times more binary digits, therefor, more accurate. But to keep 4 times more digits, there is big extra cost in carrying out operations. As one of my earlier sample codes shows, "decimal" multiply and divide are about 27 times slower than "double".