1 #include "config.h"
2 #include <assert.h>
3 #include <ccan/bitops/bitops.h>
4 #include <common/fp16.h>
5 
u64_to_fp16(u64 val,bool round_up)6 fp16_t u64_to_fp16(u64 val, bool round_up)
7 {
8 	u16 mantissa_bits, mantissa, exponent;
9 
10 	if (val == 0)
11 		return 0;
12 
13 	/* How many bits do we need to represent mantissa? */
14 	mantissa_bits = bitops_hs64(val) + 1;
15 
16 	/* We only have 11 bits, so if we need more, we will round. */
17 	if (mantissa_bits > 11) {
18 		exponent = mantissa_bits - 11;
19 		mantissa = (val >> exponent);
20 		/* If we're losing bits here, we're rounding down */
21 		if (round_up && (val & ((1ULL << exponent)-1))) {
22 			mantissa++;
23 			if (mantissa == (1 << 11)) {
24 				mantissa >>= 1;
25 				exponent++;
26 			}
27 		}
28 		/* huge number? Make it max. */
29 		if (exponent >= 32) {
30 			exponent = 31;
31 			mantissa = (1 << 11)-1;
32 		}
33 	} else {
34 		exponent = 0;
35 		mantissa = val;
36 	}
37 
38 	assert((mantissa >> 11) == 0);
39 	return (exponent << 11) | mantissa;
40 }
41 
amount_msat_less_fp16(struct amount_msat amt,fp16_t fp)42 bool amount_msat_less_fp16(struct amount_msat amt, fp16_t fp)
43 {
44 	return amt.millisatoshis < fp16_to_u64(fp); /* Raw: fp16 compare */
45 }
46 
amount_msat_greater_fp16(struct amount_msat amt,fp16_t fp)47 bool amount_msat_greater_fp16(struct amount_msat amt, fp16_t fp)
48 {
49 	return amt.millisatoshis > fp16_to_u64(fp); /* Raw: fp16 compare */
50 }
51