一个版本是
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
你期待什么value
?
0x8010 = 32784
短路的范围是-32768到32767,因此值32784不能用短路来表示.存储为0x8010的短消息将被解释为负数.这是你想要的负数吗?
根据另一个SO问题C#,十六进制表示法和有符号整数,unsafe
如果要将关键字解释为负数,则必须在C#中使用该关键字.
以下将适用于转换所有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)
归档时间: |
|
查看次数: |
6393 次 |
最近记录: |