You can be sure in a right result only if this is integer value. The type
System.UInt64
is big enough, just because 57 < 64, but not
System.UInt32
(57 > 32).
Using
Pow
function for powers of 2 is just silly. You need to shift 1 to the left using << operator, but for
System.UInt64
this is not so easy because this operator is only defined for
int
. You can do it very simply using the class
System.BitConverter
, please see:
http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx[
^].
Here is how to get an exact answer:
static System.UInt64 PowerOfTwo(byte power) {
byte[] bytes = new byte[sizeof(System.UInt64)];
int bitShift = power % 8;
int byteIndex = power / 8;
bytes[byteIndex] = (byte)(1 << bitShift);
return System.BitConverter.ToUInt64(bytes, 0);
}
Testing… the answer is 144115188075855872; your C# result was correct, SQL Server is a liar!
If you need bigger values, your only chance is the type
System.Numerics.BigInteger
; please see:
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx[
^].
—SA