帮助进行二进制算术减法

发布于 2024-10-11 17:36:34 字数 166 浏览 9 评论 0原文

假设您正在使用两个 8 位无符号值,例如来自计时器的值。如果您记录停止时间和开始时间,然后用停止时间减去开始时间来获取经过的时间,是否需要使用 mod 来处理翻转,或者减法是否有效?例如,开始时间 = 11111100 和结束时间 = 00000101 (00000101 - 11111100) 会给出正确的结果吗?

Assuming you are working with two 8-bit unsigned values like from a timer. If you record a stop time and a start time, and subtract start from stop to get the elapsed time, do you need to use mod to handle roll overs or does the subtraction just work out? For example say start time = 11111100 and the end time = 00000101 would (00000101 - 11111100) give you the correct result?

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

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

发布评论

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

评论(2

南烟 2024-10-18 17:36:34

您可以自己尝试一下,例如:

  • 开始时间 = 1111 1100 (= 252)
  • 结束时间 = 0000 0101 (= 5)

(5-252) modulo 256 = 9.

  • 结束时间 - 开始时间 = 0000 0101 - 1111 1100 = 0000 1001 (= 9)

当然,如果开始时间和结束时间相差超过 256,则此方法不起作用。您无法知道“结束时间”已经超过“开始时间”多少次,只需就像经典的溢出一样。

You can try it yourself, with your example :

  • start time = 1111 1100 (= 252)
  • end time = 0000 0101 (= 5)

(5-252) modulo 256 = 9.

  • end time - start time = 0000 0101 - 1111 1100 = 0000 1001 (= 9)

Of course, this wouldn't work if the difference between your start and end times was over 256. You can't know how many times the "end time" has gone past the "start time", just like classic overflows.

如歌彻婉言 2024-10-18 17:36:34

是的,减法的结果正如你所希望的那样。您不需要做任何特殊的事情来处理翻转。对于您的示例,减法表现良好:

00000101 - 11111100 == 00001001
(5)      - (252)    == (9)

或者:

(5+256)  - (252)    == (9)

请参阅此 Python 测试来证明这一点:

>>> all((j - i) & 0xFF == ((j & 0xFF) - i) & 0xFF
...     for i in range(256)
...     for j in range(i, i + 256))
True

j &当 j > 0xFF 项将小于 i 时。 255..这不会影响 8 位结果;这表明这些值仍然与 j 未屏蔽为 8 位时的结果匹配。

Yes, the subtraction works out as you would hope. You do not need to do anything special to handle roll over. For your example times the subtraction is well-behaved:

00000101 - 11111100 == 00001001
(5)      - (252)    == (9)

Or:

(5+256)  - (252)    == (9)

See this Python test to prove it:

>>> all((j - i) & 0xFF == ((j & 0xFF) - i) & 0xFF
...     for i in range(256)
...     for j in range(i, i + 256))
True

The j & 0xFF term will be smaller than i when j > 255. That does not affect the 8-bit results; this shows that those values still match the results for when j is not masked to 8 bits.

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