如何在C#中将ushort转换为short?

Big*_*ser 1 .net c#

一个版本是

short value = unchecked((short)0x8010);
Run Code Online (Sandbox Code Playgroud)

像下面这样的其他版本将无法正常工作,并会抛出异常

short value = Convert.ToInt16(0x8010);
short value = (short)(0x8010);
Run Code Online (Sandbox Code Playgroud)

有没有未经检查的关键字的其他版本?

更新:预期为负值-32752

And*_*bel 7

你期待什么value

0x8010 = 32784

短路的范围是-32768到32767,因此值32784不能用短路来表示.存储为0x8010的短消息将被解释为负数.这是你想要的负数吗?

根据另一个SO问题C#,十六进制表示法和有符号整数,unsafe如果要将关键字解释为负数,则必须在C#中使用该关键字.


Jar*_*Par 5

以下将适用于转换所有ushort适合short和替换所有值的值short.MaxValue.这是有损转换.

ushort source = ...;
short value = source > (ushort)short.MaxValue
  ? short.MaxValue
  : (short)source;
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找直接位转换,您可以执行以下操作(但我不建议这样做)

[StructLayout(LayoutKind.Explicit)]
struct EvilConverter
{
    [FieldOffset(0)] short ShortValue;
    [FieldOffset(0)] ushort UShortValue;

    public static short Convert(ushort source)
    {
        var converter = new EvilConverter();
        converter.UShortValue = source;
        return converter.ShortValue;
    }
}
Run Code Online (Sandbox Code Playgroud)