简体   繁体   中英

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?

Updated : expected is negative value of -32752

What do you expect value to be?

0x8010 = 32784

The range of a short is -32768 to 32767 so the value 32784 cannot be expressed by a short. A short stored as 0x8010 will be interpreted as a negative number. 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.

The following will work to convert all ushort values which fit into short and replace all values which don't with 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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