[英]How do I convert ushort to short in C#?
一個版本是
short value = unchecked((short)0x8010);
像下面這樣的其他版本將不起作用,並且會拋出異常
short value = Convert.ToInt16(0x8010);
short value = (short)(0x8010);
有沒有其他版本沒有 unchecked 關鍵字?
更新:預期為負值 -32752
你期望的value
是多少?
0x8010 = 32784
short 的范圍是 -32768 到 32767,因此值 32784 不能用 short 表示。 存儲為 0x8010 的 short 將被解釋為負數。 是你想要的負數嗎?
根據另一個 SO 問題C#,十六進制表示法和有符號整數,如果您希望將其解釋為負數,則必須在 C# 的這種情況下使用unsafe
關鍵字。
以下將用於將所有適合的ushort
值轉換為short
並將所有不適合的值替換為short.MaxValue
。 這是有損轉換。
ushort source = ...;
short value = source > (ushort)short.MaxValue
? short.MaxValue
: (short)source;
如果您正在尋找直接位轉換,您可以執行以下操作(但我不推薦它)
[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;
}
}
我會建議:
ushort input;
short output;
output = short.Parse(input.ToString("X"), NumberStyles.HexNumber));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.