Skip to content

Commit a98676c

Browse files
committed
Fixed all conversion issues, fixes #96.
1 parent d3ff29b commit a98676c

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

src/SparkplugNet/Core/Extensions/DataTypeExtensions.cs

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,44 @@ internal static class DataTypeExtensions
2828
}
2929

3030
// Check whether we need to convert from signed to unsigned.
31-
var needToConvertFromSignedToUnsigned =
32-
(objValue is sbyte sbyteVal && sbyteVal < 0) ||
33-
(objValue is short shortVal && shortVal < 0) ||
34-
(objValue is int intVal && intVal < 0) ||
35-
(objValue is long longVal && longVal < 0);
31+
if (objValue is sbyte sbyteVal && sbyteVal < 0)
32+
{
33+
return typeof(T) switch
34+
{
35+
Type t when t == typeof(uint) => (T)Convert.ChangeType(unchecked((uint)sbyteVal), typeof(T)),
36+
Type t when t == typeof(ulong) => (T)Convert.ChangeType(unchecked((ulong)sbyteVal), typeof(T)),
37+
_ => unchecked((T)objValue),
38+
};
39+
}
40+
41+
if (objValue is short shortVal && shortVal < 0)
42+
{
43+
return typeof(T) switch
44+
{
45+
Type t when t == typeof(uint) => (T)Convert.ChangeType(unchecked((uint)shortVal), typeof(T)),
46+
Type t when t == typeof(ulong) => (T)Convert.ChangeType(unchecked((ulong)shortVal), typeof(T)),
47+
_ => unchecked((T)objValue),
48+
};
49+
}
50+
51+
if (objValue is int intVal && intVal < 0)
52+
{
53+
return typeof(T) switch
54+
{
55+
Type t when t == typeof(uint) => (T)Convert.ChangeType(unchecked((uint)intVal), typeof(T)),
56+
Type t when t == typeof(ulong) => (T)Convert.ChangeType(unchecked((ulong)intVal), typeof(T)),
57+
_ => unchecked((T)objValue),
58+
};
59+
}
3660

37-
if (needToConvertFromSignedToUnsigned)
61+
if (objValue is long longVal && longVal < 0)
3862
{
39-
return unchecked((T)objValue);
63+
return typeof(T) switch
64+
{
65+
Type t when t == typeof(uint) => (T)Convert.ChangeType(unchecked((uint)longVal), typeof(T)),
66+
Type t when t == typeof(ulong) => (T)Convert.ChangeType(unchecked((ulong)longVal), typeof(T)),
67+
_ => unchecked((T)objValue),
68+
};
4069
}
4170

4271
// Check whether we need to convert from unsigned to signed.

0 commit comments

Comments
 (0)