简体   繁体   English

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

[英]How do I convert ushort to short in C#?

One version is一个版本是

short value = unchecked((short)0x8010);

Other versions like below will not work, and will throw an exceptions像下面这样的其他版本将不起作用,并且会抛出异常

short value = Convert.ToInt16(0x8010);
short value = (short)(0x8010);

Is there any other version without unchecked keyword?有没有其他版本没有 unchecked 关键字?

Updated : expected is negative value of -32752更新:预期为负值 -32752

What do you expect value to be?你期望的value是多少?

0x8010 = 32784

The range of a short is -32768 to 32767 so the value 32784 cannot be expressed by a short. short 的范围是 -32768 到 32767,因此值 32784 不能用 short 表示。 A short stored as 0x8010 will be interpreted as a negative number.存储为 0x8010 的 short 将被解释为负数。 Is it that negative number you want?是你想要的负数吗?

According to another SO question C#, hexadecimal notation and signed integers the unsafe keyword must be used in this case in C# if you want it to be interpreted as a negative number.根据另一个 SO 问题C#,十六进制表示法和有符号整数,如果您希望将其解释为负数,则必须在 C# 的这种情况下使用unsafe关键字。

The following will work to convert all ushort values which fit into short and replace all values which don't with short.MaxValue .以下将用于将所有适合的ushort值转换为short并将所有不适合的值替换为short.MaxValue This is lossy conversion though.这是有损转换。

ushort source = ...;
short value = source > (ushort)short.MaxValue
  ? short.MaxValue
  : (short)source;

If you are looking for a straight bit conversion you can do the following (but I wouldn't recommend it)如果您正在寻找直接位转换,您可以执行以下操作(但我不推荐它)

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

I would suggest:我会建议:

ushort input;
short output;
output = short.Parse(input.ToString("X"), NumberStyles.HexNumber));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM