I am trying to map ulong to long (and vice versa) and uint to int (and vice versa) as shown below - in order to store values ββin an MS-SQL database with signed types only integer and large integer.
I do this because I have to check (in the database) whether the number (uint, ulong) is within what range in the range of uint / ulong ranges (IP addresses are v4 and v6; actually ulong actually represents itself uint128, consisting of two oolongs).


Is there a more efficient way to do this than the code I'm 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); }
user7212775
source share