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

标签 c# .net

一个版本是

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

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

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

有没有没有unchecked keyword的其他版本?

已更新:预期为负值 -32752

最佳答案

您期望是什么?

0x8010 = 32784

short 的范围是 -32768 到 32767,所以值 32784 不能用 short 表示。存储为 0x8010 的短整数将被解释为负数。是您想要的那个负数吗?

根据另一个 SO 问题 C#, hexadecimal notation and signed integers如果您希望它被解释为负数,则必须在 C# 中使用 unsafe 关键字。

关于c# - 如何在 C# 中将 ushort 转换为 short?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7017105/

相关文章:

javascript - DataSourceRequest 将属性添加到 GridView 剑道

.net - ASP.NET 中的 REST WCF 服务和 session

.net - 如何将包含日期的字符串转换为不同的格式?

c# - Windows 中挂起/恢复时套接字会发生什么

c# - Entity Framework EF4.1 - 存储过程 "could not be found in the container"

c# - 确定 Request.Form 中的控件类型

c# - 随机不工作

c# - 创建没有委托(delegate)的线程 - 为什么这有效?

c# - 从 FormsAuthentication.Authenticate 中删除用户名/密码的区分大小写

c# - 检测到包将 : Microsoft. NETCore.App 从 2.1.3 降级到 2.1.0