Mapping a ulong to a long in C#?
To map from ulong
to long
, cast and add long.MinValue
. To map from long
back to ulong
, subtract long.MinValue
and cast. In either case, use an unchecked context so that overflow conditions are ignored.
public static long MapUlongToLong(ulong ulongValue)
{
return unchecked((long)ulongValue + long.MinValue);
}
public static ulong MapLongToUlong(long longValue)
{
return unchecked((ulong)(longValue - long.MinValue));
}
The logic for uint
and int
is exactly analogous.