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