xref: /freebsd/contrib/ntp/libntp/refidsmear.c (revision b5ff185e19f6013ca565b2a15bc2d6abce933f46)
1*276da39aSCy Schubert #include <config.h>
2*276da39aSCy Schubert 
3*276da39aSCy Schubert #include <ntp.h>
4*276da39aSCy Schubert #include <ntp_fp.h>
5*276da39aSCy Schubert #include <refidsmear.h>
6*276da39aSCy Schubert 
7*276da39aSCy Schubert /*
8*276da39aSCy Schubert  * we want to test a refid format of:
9*276da39aSCy Schubert  * 254.x.y.x
10*276da39aSCy Schubert  *
11*276da39aSCy Schubert  * where x.y.z are 24 bits containing 2 (signed) integer bits
12*276da39aSCy Schubert  * and 22 fractional bits.
13*276da39aSCy Schubert  *
14*276da39aSCy Schubert  */
15*276da39aSCy Schubert 
16*276da39aSCy Schubert 
17*276da39aSCy Schubert l_fp
convertRefIDToLFP(uint32_t r)18*276da39aSCy Schubert convertRefIDToLFP(uint32_t r)
19*276da39aSCy Schubert {
20*276da39aSCy Schubert 	l_fp temp;
21*276da39aSCy Schubert 
22*276da39aSCy Schubert 	r = ntohl(r);
23*276da39aSCy Schubert 
24*276da39aSCy Schubert 	// printf("%03d %08x: ", (r >> 24) & 0xFF, (r & 0x00FFFFFF) );
25*276da39aSCy Schubert 
26*276da39aSCy Schubert 	temp.l_uf = (r << 10);	/* 22 fractional bits */
27*276da39aSCy Schubert 
28*276da39aSCy Schubert 	temp.l_ui = (r >> 22) & 0x3;
29*276da39aSCy Schubert 	temp.l_ui |= ~(temp.l_ui & 2) + 1;
30*276da39aSCy Schubert 
31*276da39aSCy Schubert 	return temp;
32*276da39aSCy Schubert }
33*276da39aSCy Schubert 
34*276da39aSCy Schubert 
35*276da39aSCy Schubert uint32_t
convertLFPToRefID(l_fp num)36*276da39aSCy Schubert convertLFPToRefID(l_fp num)
37*276da39aSCy Schubert {
38*276da39aSCy Schubert 	uint32_t temp;
39*276da39aSCy Schubert 
40*276da39aSCy Schubert 	/* round the input with the highest bit to shift out from the
41*276da39aSCy Schubert 	 * fraction, then keep just two bits from the integral part.
42*276da39aSCy Schubert 	 *
43*276da39aSCy Schubert 	 * TODO: check for overflows; should we clamp/saturate or just
44*276da39aSCy Schubert 	 * complain?
45*276da39aSCy Schubert 	 */
46*276da39aSCy Schubert 	L_ADDUF(&num, 0x200);
47*276da39aSCy Schubert 	num.l_ui &= 3;
48*276da39aSCy Schubert 
49*276da39aSCy Schubert 	/* combine integral and fractional part to 24 bits */
50*276da39aSCy Schubert 	temp  = (num.l_ui << 22) | (num.l_uf >> 10);
51*276da39aSCy Schubert 
52*276da39aSCy Schubert 	/* put in the leading 254.0.0.0 */
53*276da39aSCy Schubert 	temp |= UINT32_C(0xFE000000);
54*276da39aSCy Schubert 
55*276da39aSCy Schubert 	// printf("%03d %08x: ", (temp >> 24) & 0xFF, (temp & 0x00FFFFFF) );
56*276da39aSCy Schubert 
57*276da39aSCy Schubert 	return htonl(temp);
58*276da39aSCy Schubert }
59