1290001Sglebius#include <config.h>
2290001Sglebius
3290001Sglebius#include <ntp.h>
4290001Sglebius#include <ntp_fp.h>
5290001Sglebius#include <refidsmear.h>
6290001Sglebius
7290001Sglebius/*
8290001Sglebius * we want to test a refid format of:
9290001Sglebius * 254.x.y.x
10290001Sglebius *
11290001Sglebius * where x.y.z are 24 bits containing 2 (signed) integer bits
12290001Sglebius * and 22 fractional bits.
13290001Sglebius *
14290001Sglebius */
15290001Sglebius
16290001Sglebius
17290001Sglebiusl_fp
18290001SglebiusconvertRefIDToLFP(uint32_t r)
19290001Sglebius{
20290001Sglebius	l_fp temp;
21290001Sglebius
22290001Sglebius	r = ntohl(r);
23290001Sglebius
24290001Sglebius	// printf("%03d %08x: ", (r >> 24) & 0xFF, (r & 0x00FFFFFF) );
25290001Sglebius
26290001Sglebius	temp.l_uf = (r << 10);	/* 22 fractional bits */
27290001Sglebius
28290001Sglebius	temp.l_ui = (r >> 22) & 0x3;
29290001Sglebius	temp.l_ui |= ~(temp.l_ui & 2) + 1;
30290001Sglebius
31290001Sglebius	return temp;
32290001Sglebius}
33290001Sglebius
34290001Sglebius
35290001Sglebiusuint32_t
36290001SglebiusconvertLFPToRefID(l_fp num)
37290001Sglebius{
38290001Sglebius	uint32_t temp;
39290001Sglebius
40290001Sglebius	/* round the input with the highest bit to shift out from the
41290001Sglebius	 * fraction, then keep just two bits from the integral part.
42290001Sglebius	 *
43290001Sglebius	 * TODO: check for overflows; should we clamp/saturate or just
44290001Sglebius	 * complain?
45290001Sglebius	 */
46290001Sglebius	L_ADDUF(&num, 0x200);
47290001Sglebius	num.l_ui &= 3;
48290001Sglebius
49290001Sglebius	/* combine integral and fractional part to 24 bits */
50290001Sglebius	temp  = (num.l_ui << 22) | (num.l_uf >> 10);
51290001Sglebius
52290001Sglebius	/* put in the leading 254.0.0.0 */
53290001Sglebius	temp |= UINT32_C(0xFE000000);
54290001Sglebius
55290001Sglebius	// printf("%03d %08x: ", (temp >> 24) & 0xFF, (temp & 0x00FFFFFF) );
56290001Sglebius
57290001Sglebius	return htonl(temp);
58290001Sglebius}
59