1284990Scy#include <config.h>
2284990Scy
3284990Scy#include <ntp.h>
4284990Scy#include <ntp_fp.h>
5284990Scy#include <refidsmear.h>
6284990Scy
7284990Scy/*
8284990Scy * we want to test a refid format of:
9284990Scy * 254.x.y.x
10284990Scy *
11284990Scy * where x.y.z are 24 bits containing 2 (signed) integer bits
12284990Scy * and 22 fractional bits.
13284990Scy *
14284990Scy */
15284990Scy
16284990Scy
17284990Scyl_fp
18284990ScyconvertRefIDToLFP(uint32_t r)
19284990Scy{
20284990Scy	l_fp temp;
21284990Scy
22284990Scy	r = ntohl(r);
23284990Scy
24284990Scy	// printf("%03d %08x: ", (r >> 24) & 0xFF, (r & 0x00FFFFFF) );
25284990Scy
26284990Scy	temp.l_uf = (r << 10);	/* 22 fractional bits */
27284990Scy
28284990Scy	temp.l_ui = (r >> 22) & 0x3;
29284990Scy	temp.l_ui |= ~(temp.l_ui & 2) + 1;
30284990Scy
31284990Scy	return temp;
32284990Scy}
33284990Scy
34284990Scy
35284990Scyuint32_t
36284990ScyconvertLFPToRefID(l_fp num)
37284990Scy{
38284990Scy	uint32_t temp;
39284990Scy
40284990Scy	/* round the input with the highest bit to shift out from the
41284990Scy	 * fraction, then keep just two bits from the integral part.
42284990Scy	 *
43284990Scy	 * TODO: check for overflows; should we clamp/saturate or just
44284990Scy	 * complain?
45284990Scy	 */
46284990Scy	L_ADDUF(&num, 0x200);
47284990Scy	num.l_ui &= 3;
48284990Scy
49284990Scy	/* combine integral and fractional part to 24 bits */
50284990Scy	temp  = (num.l_ui << 22) | (num.l_uf >> 10);
51284990Scy
52284990Scy	/* put in the leading 254.0.0.0 */
53284990Scy	temp |= UINT32_C(0xFE000000);
54284990Scy
55284990Scy	// printf("%03d %08x: ", (temp >> 24) & 0xFF, (temp & 0x00FFFFFF) );
56284990Scy
57284990Scy	return htonl(temp);
58284990Scy}
59