开发者

help with binary arithmetic subtraction

Assumin开发者_如何转开发g 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜