在 C# 中将无符号 16 位 int 转换为有符号 16 位 int

发布于 2024-08-19 22:10:14 字数 236 浏览 2 评论 0原文

我正在为机器人控制器编写一个数据日志解析器,从数据日志中输入的是 0 - 65535 范围内的数字(如果我没有记错的话,这是一个 16 位无符号整数)。我正在尝试将其转换为带符号的 16 位整数以显示给用户(因为这是记录器更改之前的实际数据类型)。

有人可以帮我吗?

示例:

值应该是什么 (0, -1, -2, -3, -4)

值是什么 (0、65535、65534、65533、65532)

I'm writing a datalog parser for a robot controller, and what's coming in from the data log is a number in the range of 0 - 65535 (which is a 16 bit unsigned integer if I'm not mistaken). I'm trying to convert that to a signed 16 bit integer to display to the user (since that was the actual datatype before the logger changed it).

Can someone give me a hand?

Example:

What the values should be
(0, -1, -2, -3, -4)

What the values are
(0, 65535, 65534, 65533, 65532)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自由范儿 2024-08-26 22:10:14

您尝试过显式强制转换吗?

UInt16 x = 65535;
var y = (Int16)x; // y = -1

Have you tried explicit casting?

UInt16 x = 65535;
var y = (Int16)x; // y = -1
国际总奸 2024-08-26 22:10:14

如果启用了[X]检查算术溢出,则在此处使用unchecked可以避免崩溃:

UInt16 x = 65535;
Int16 y = unchecked((Int16)x);

Using unchecked here avoids a crash if [X] Check for Arithmetic Overflow is on:

UInt16 x = 65535;
Int16 y = unchecked((Int16)x);
困倦 2024-08-26 22:10:14

或者像这样

“或者像这样”

只需检查是否UI16>32767如果是,I16=UI16-65536,否则=UI16

Or like this

Or like this

Just check if UI16>32767 if yes, I16=UI16-65536, otherwise = UI16

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文