如何将一些负数转换为unsigned types
.
Type type = typeof (ushort);
short num = -100;
ushort num1 = unchecked ((ushort) num); //When type is known. Result 65436
ushort num2 = unchecked(Convert.ChangeType(num, type)); //Need here the same value
只有4种类型。因此,您可以为此编写自己的方法。
private static object CastToUnsigned(object number)
{
Type type = number.GetType();
unchecked
{
if (type == typeof(int)) return (uint)(int)number;
if (type == typeof(long)) return (ulong)(long)number;
if (type == typeof(short)) return (ushort)(short)number;
if (type == typeof(sbyte)) return (byte)(sbyte)number;
}
return null;
}
这是测试:
short sh = -100;
int i = -100;
long l = -100;
Console.WriteLine(CastToUnsigned(sh));
Console.WriteLine(CastToUnsigned(i));
Console.WriteLine(CastToUnsigned(l));
Outputs
65436
4294967196
18446744073709551516
更新 10/10/2017
通过 C# 7.1 泛型类型的模式匹配功能,您现在可以使用 switch 语句。
感谢@quinmars 的建议。
private static object CastToUnsigned<T>(T number) where T : struct
{
unchecked
{
switch (number)
{
case long xlong: return (ulong) xlong;
case int xint: return (uint)xint;
case short xshort: return (ushort) xshort;
case sbyte xsbyte: return (byte) xsbyte;
}
}
return number;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)