简体   繁体   English

帮助二进制算术减法

[英]help with binary arithmetic subtraction

Assuming you are working with two 8-bit unsigned values like from a timer. 假设您正在使用两个8位无符号值,例如来自计时器的值。 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? 如果您记录了停止时间和开始时间,并从停止中减去开始时间以获取经过的时间,那么您是否需要使用mod来处理翻转或减法是否可行? For example say start time = 11111100 and the end time = 00000101 would (00000101 - 11111100) give you the correct result? 例如,说开始时间= 11111100,结束时间= 00000101(00000101-11111100)将为您提供正确的结果?

You can try it yourself, with your example : 您可以使用示例自己尝试:

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

(5-252) modulo 256 = 9. (5-252)模256 = 9。

  • end time - start time = 0000 0101 - 1111 1100 = 0000 1001 (= 9) 结束时间-开始时间= 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. 当然,如果开始时间和结束时间之间的差超过256,则将无法正常工作。您无法知道“结束时间”超过“开始时间”的次数,就像经典的溢出一样。

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: 请参阅此Python测试以证明这一点:

>>> 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 . j > 255时, j & 0xFF项将小于i That does not affect the 8-bit results; 这不会影响8位结果; this shows that those values still match the results for when j is not masked to 8 bits. 这表明当j不被掩码为8位时,这些值仍与结果匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM