gpt4 book ai didi

c# - 将负数转换为无符号类型(ushort、uint 或 ulong)

转载 作者:行者123 更新时间:2023-11-30 16:05:37 34 4
gpt4 key购买 nike

如何将一些负数转换为无符号类型

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));

输出

65436
4294967196
18446744073709551516

2017 年 10 月 10 日更新

借助适用于泛型类型的 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;
}

关于c# - 将负数转换为无符号类型(ushort、uint 或 ulong),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33243440/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com