1. ## Circular counter

hi guys:

i'm new to the forum and i was hoping to see if someone can help me out.

i'm reading a usb stream, and each packet has a 2 byte counter.(from 0x0000 to 0xffff). this counter is circular.

i have 3 counters: oldCounter, newCounter and auxCounter.

everytime i find a counter on the stream, i store the old newCounter value to auxCounter:
Code:
`__int16 auxCounter = newCounter;`
then i read the 2 bytes to the newCounter:
Code:
```newCounter = (__int16)buffer[i+1] << 8;
newCounter += buffer[i+2];```
since the stream can have random counters, i only assign the old newCounter value to oldCounter is it's a valid counter i.e. if the new counter value is greater than the oldCounter value.

Code:
``` if(newCounter > oldCounter )
{
oldCounter=auxCounter;
}```
i then check if :

Code:
```if(newCounter != oldCounter+1)
{
}```
My problem is in the 3rd code snippet.

if for instance the oldCounter has the value 0xFFFF, thew next packet will have counter = 0x0000 (and it's a valid packet) but the condition if(newCounter > oldCounter ) will fail and i'll start to have bad results.

so my question is if anyone can help me out sorting a way to check if the new countr is greater than the old but in a circular way, for instance:

oldCounter = 0xfffff

newCounter = 0x0000

Code:
` if(newCounter > oldCounter )   -> return true`

2. >> so my question is if anyone can help me out sorting a way to check if the new countr is greater than the old but in a circular way

I'm not sure I understand what exactly you're trying to do here. It might help if you posted a stripped down (and compilable) demonstration program so that we can see more clearly what the issue is.

3. What you want doesn't make much sense. See, *every* value is greater than *every* other in a circular way. 0xFFFE is greater than 0xFFFF like that. If you want to check if it has a difference of one, just do
something == something2 + 1
(note: make the values a uint16, not an int16)

If you want to test for a specific range, eg. make sure that this sequence number is within 20 of the old one, try:
new - old <= 20

4. Originally Posted by EVOEx
What you want doesn't make much sense. See, *every* value is greater than *every* other in a circular way. 0xFFFE is greater than 0xFFFF like that.
ye just realized that

Originally Posted by EVOEx
If you want to test for a specific range, eg. make sure that this sequence number is within 20 of the old one, try:
new - old <= 20
will have to use something like this i suppose.

`diff = newCounter - oldCounter;`