N
Noob
Hello,
Consider the following scenario.
'A' produces data which are sent in "packets" to 'B'.
Each "packet" carries a sequence number, so that 'B' can
insert the packet in the "right place" in a sorted list.
The sequence number of the 1st packet is 0.
The sequence number of the 65536th packet is 65535.
The sequence number of the 65537th packet "wraps around" back to 0.
Because of the wrap-around, I can't just use the normal relational
operators. For example, with very high probability, seqno 0 is newer
than seqno 65535, which translates to : 0 "is greater than" 65535.
Given a sequence number 'u'
u+1, u+2, ..., u+32767 (mod 65536) are considered greater than u.
u-1, u-2, ..., u-32768 (mod 65536) are considered lower than u.
I have implemented this as :
#include <stdint.h>
int greater_than(uint16_t u, uint16_t v)
{
return (int16_t)(u-v) > 0;
}
This works on my platform (GCC, Linux, x86) but AFAIU, conversion
from unsigned to signed integer is undefined?
Is there a way to implement the comparison function in a
portable manner?
Regards.
Consider the following scenario.
'A' produces data which are sent in "packets" to 'B'.
Each "packet" carries a sequence number, so that 'B' can
insert the packet in the "right place" in a sorted list.
The sequence number of the 1st packet is 0.
The sequence number of the 65536th packet is 65535.
The sequence number of the 65537th packet "wraps around" back to 0.
Because of the wrap-around, I can't just use the normal relational
operators. For example, with very high probability, seqno 0 is newer
than seqno 65535, which translates to : 0 "is greater than" 65535.
Given a sequence number 'u'
u+1, u+2, ..., u+32767 (mod 65536) are considered greater than u.
u-1, u-2, ..., u-32768 (mod 65536) are considered lower than u.
I have implemented this as :
#include <stdint.h>
int greater_than(uint16_t u, uint16_t v)
{
return (int16_t)(u-v) > 0;
}
This works on my platform (GCC, Linux, x86) but AFAIU, conversion
from unsigned to signed integer is undefined?
Is there a way to implement the comparison function in a
portable manner?
Regards.