aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Common/Utilities/BitUtils.cs
blob: 0bf9c8acdeb37992d4acee011ce9f79531d4285d (plain) (blame)
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
using System.Numerics;

namespace Ryujinx.Common
{
    public static class BitUtils
    {
        public static T AlignUp<T>(T value, T size)
            where T : IBinaryInteger<T>
        {
            return (value + (size - T.One)) & -size;
        }

        public static T AlignDown<T>(T value, T size)
            where T : IBinaryInteger<T>
        {
            return value & -size;
        }

        public static T DivRoundUp<T>(T value, T dividend)
            where T : IBinaryInteger<T>
        {
            return (value + (dividend - T.One)) / dividend;
        }

        public static int Pow2RoundUp(int value)
        {
            value--;

            value |= (value >> 1);
            value |= (value >> 2);
            value |= (value >> 4);
            value |= (value >> 8);
            value |= (value >> 16);

            return ++value;
        }

        public static int Pow2RoundDown(int value)
        {
            return BitOperations.IsPow2(value) ? value : Pow2RoundUp(value) >> 1;
        }

        public static long ReverseBits64(long value)
        {
            return (long)ReverseBits64((ulong)value);
        }

        private static ulong ReverseBits64(ulong value)
        {
            value = ((value & 0xaaaaaaaaaaaaaaaa) >> 1) | ((value & 0x5555555555555555) << 1);
            value = ((value & 0xcccccccccccccccc) >> 2) | ((value & 0x3333333333333333) << 2);
            value = ((value & 0xf0f0f0f0f0f0f0f0) >> 4) | ((value & 0x0f0f0f0f0f0f0f0f) << 4);
            value = ((value & 0xff00ff00ff00ff00) >> 8) | ((value & 0x00ff00ff00ff00ff) << 8);
            value = ((value & 0xffff0000ffff0000) >> 16) | ((value & 0x0000ffff0000ffff) << 16);

            return (value >> 32) | (value << 32);
        }
    }
}