将负数转换为无符号类型(ushort、uint 或 ulong) [英] Cast negative number to unsigned types (ushort, uint or ulong)

查看:550
本文介绍了将负数转换为无符号类型(ushort、uint 或 ulong)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to cast some negative number to 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 种类型.因此,您可以为此编写自己的方法.

There are only 4 types. so simply you can write your own method for that.

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 语句.

with C# 7.1 pattern matching feature for generic types you can now use switch statement.

感谢@quinmars 的建议.

thanks to @quinmars for his suggestion.

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

这篇关于将负数转换为无符号类型(ushort、uint 或 ulong)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆