-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtil.cs
64 lines (58 loc) · 2.03 KB
/
Util.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
namespace WireguardAllowedIPs.Core;
internal static class Util
{
/// <summary>
/// Counts the minimum number of bits needed to represent this 32-bit integer value.
/// i.e. if a certain number of high bits are zero, the result will be less than 32
/// </summary>
/// <param name="value">The value in question</param>
/// <returns>Number of bits</returns>
public static int BitLength32(uint value)
{
int bitLength = 0;
while ((value >> bitLength) > 0 && bitLength < 32)
{
bitLength++;
}
return bitLength;
}
/// <summary>
/// Counts the number of zeros after the highest set bit up until 32.
/// i.e. if a certain number of high bits are zero, the result will be that amount
/// </summary>
/// <param name="value">The value in question</param>
/// <returns>Number of bits</returns>
public static int CountRighthandZeroBits32(uint value)
{
if (value == 0)
return 32;
return BitLength32(~value & (value - 1));
}
/// <summary>
/// Counts the minimum number of bits needed to represent this 128-bit integer value.
/// i.e. if a certain number of high bits are zero, the result will be less than 128
/// </summary>
/// <param name="value">The value in question</param>
/// <returns>Number of bits</returns>
public static int BitLength128(UInt128 value)
{
int bitLength = 0;
while ((value >> bitLength) > 0 && bitLength < 128)
{
bitLength++;
}
return bitLength;
}
/// <summary>
/// Counts the number of zeros after the highest set bit up until 128.
/// i.e. if a certain number of high bits are zero, the result will be that amount
/// </summary>
/// <param name="value">The value in question</param>
/// <returns>Number of bits</returns>
public static int CountRighthandZeroBits128(UInt128 value)
{
if (value == 0)
return 128;
return BitLength128(~value & (value - 1));
}
}