c++ - rollover issue with unsigned int while checking if a number is within a range -
i trying check if received message number in given range. everytime message number gets incremented.so if expecting number 10, accept message number 10+ 5. sequence numbers 10 15. using unsigned int. when expected number 65532,i can accept 65532 + 10(so min = 65532 , max = 5). how check if number received in range?
if use unsigned
gf(2k) arithmetic value k [edit: addition , subtraction, doing full finite field more work; maybe should adopt other shorthand terminology?]. typically unsigned short
k 16, unsigned int
32, , unsigned long long
64, in case @ least 16 (because uint_max
@ least 65535).
in kind of finite field arithmetic can subtract 2 numbers , compare result against limit. is, if range of "allowed values" x x+5 , actual value received y, then:
unsigned int x, y, diff; ... diff = y - x; if (diff <= 5) { value in range } else { value out of range }
this works fine long "in range" window not exceed 2k-1, , since k >= 16 means window space @ least 32767.
if wish use unsigned short
1 wrinkle in c unsigned short
expands (signed, plain) int
instead of unsigned int
in usual case, when int_max >= ushrt_max
. have cast unsigned int
subtraction:
unsigned short x, y, diff; .... diff = (unsigned int)y - (unsigned int)x;
the rest of code unchanged (note assigning unsigned int
unsigned short
defined reduces value mod 2k).
Comments
Post a Comment