I am trying to map a ulong to a long (and vice-versa), and a uint to a int (and vice-versa), as shown below - in order to save the values in a MS-SQL-database with signed types integer and biginteger only.
I do this because I have to check (in the database) whether a number (uint, ulong) is within which range in a bunch of uint/ulong ranges (IPs - v4 & v6; actually the ulong is in reality a uint128 composed of two ulongs).
Is there a more efficient way to accomplish this than the code I have here:
public static ulong SignedLongToUnsignedLong(long signedLongValue)
{
ulong backConverted = 0;
// map ulong to long [ 9223372036854775808 = abs(long.MinValue) ]
if (signedLongValue < 0)
{
// Cannot take abs from MinValue
backConverted = (ulong)System.Math.Abs(signedLongValue - 1);
backConverted = 9223372036854775808 - backConverted - 1;
}
else
{
backConverted = (ulong)signedLongValue;
backConverted += 9223372036854775808;
}
return backConverted;
}
public static long UnsignedLongToSignedLong(ulong unsignedLongValue)
{
// map ulong to long [ 9223372036854775808 = abs(long.MinValue) ]
return (long) (unsignedLongValue - 9223372036854775808);
}
public static int UnsignedIntToSignedInt(uint unsignedIntValue)
{
// map uint to int [ 2147483648 = abs(long.MinValue) ]
return (int)(unsignedIntValue - 2147483648);
}
public static uint SignedIntToUnsignedInt(int signedIntValue)
{
uint backConverted = 0;
// map ulong to long [ 2147483648 = abs(long.MinValue) ]
if (signedIntValue < 0)
{
// Cannot take abs from MinValue
backConverted = (uint)System.Math.Abs(signedIntValue - 1);
backConverted = 2147483648 - backConverted - 1;
}
else
{
backConverted = (uint)signedIntValue;
backConverted += 2147483648;
}
return backConverted;
}
public static void TestLong()
{
long min_long = -9223372036854775808;
long max_long = 9223372036854775807;
ulong min_ulong = ulong.MinValue; // 0
ulong max_ulong = ulong.MaxValue; // 18446744073709551615 = (2^64)-1
long dbValueMin = UnsignedLongToSignedLong(min_ulong);
long dbValueMax = UnsignedLongToSignedLong(max_ulong);
ulong valueFromDbMin = SignedLongToUnsignedLong(dbValueMin);
ulong valueFromDbMax = SignedLongToUnsignedLong(dbValueMax);
System.Console.WriteLine(dbValueMin);
System.Console.WriteLine(dbValueMax);
System.Console.WriteLine(valueFromDbMin);
System.Console.WriteLine(valueFromDbMax);
}
public static void TestInt()
{
int min_int = -2147483648; // int.MinValue
int max_int = 2147483647; // int.MaxValue
uint min_uint= uint.MinValue; // 0
uint max_uint = uint.MaxValue; // 4294967295 = (2^32)-1
int dbValueMin = UnsignedIntToSignedInt(min_uint);
int dbValueMax = UnsignedIntToSignedInt(max_uint);
uint valueFromDbMin = SignedIntToUnsignedInt(dbValueMin);
uint valueFromDbMax = SignedIntToUnsignedInt(dbValueMax);
System.Console.WriteLine(dbValueMin);
System.Console.WriteLine(dbValueMax);
System.Console.WriteLine(valueFromDbMin);
System.Console.WriteLine(valueFromDbMax);
}