Everyone knows there is a size difference between a gigabyte of memory, and a gigabyte of disk space.
The former is 1024*1024*1024, the latter is 1000*1000*1000.
To facilitate this, I’ve created a C# class UnitPrefixes containing quite a few constants and readonly values.
The class is below, but a few interesting facts first:
- Most values are const, but a few are readonly static variables because they cannot calculated at compile time (the C# compiler by design does very limited calculations at compile time; it is complex enough as it already is).
As Jon Skeet explains, there are some other differences between const and readonly static, which is why I favour const.
- Though all consts are positive, I could have used UInt32 and UInt64, but the .NET framework favours signed Int32 and Int64 types for parameters, so to avoid casting, I used the signed ones.
- There is no Int128 or UInt128, but there is System.Numerics.BigInteger which I use for values too large for 64-bit integers.
Note that BigInteger is relatively new, so this code will only work in C# 4 or higher, and requires .NET 4 or higher.
This is also the place where I use the public readonly static fields, as I need to call the BigInteger constructor to initialize it.
- I used the Decimal type, as the mantissa holds up to 28 digits of accuracy.
Note that BitsPerByte is a const I needed too, and I will probably add constants for 512 and 4096, as you see those often in computing as well.