帮助进行二进制算术减法
假设您正在使用两个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以自己尝试一下,例如:
(5-252) modulo 256 = 9.
当然,如果开始时间和结束时间相差超过 256,则此方法不起作用。您无法知道“结束时间”已经超过“开始时间”多少次,只需就像经典的溢出一样。
You can try it yourself, with your example :
(5-252) modulo 256 = 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.
是的,减法的结果正如你所希望的那样。您不需要做任何特殊的事情来处理翻转。对于您的示例,减法表现良好:
或者:
请参阅此 Python 测试来证明这一点:
j &当
.这不会影响 8 位结果;这表明这些值仍然与j > 0xFF
项将小于i
时。 255.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:
Or:
See this Python test to prove it:
The
j & 0xFF
term will be smaller thani
whenj > 255
. That does not affect the 8-bit results; this shows that those values still match the results for whenj
is not masked to 8 bits.