summary refs log tree commit diff
path: root/crypto/src/util/Longs.cs
blob: d206c1f818f7729d7ec2db26ac37836b50ec8bb9 (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
60
61
62
63
64
65
using System;

using Org.BouncyCastle.Math.Raw;

namespace Org.BouncyCastle.Utilities
{
    public abstract class Longs
    {
        public static long Reverse(long i)
        {
            i = (long)Bits.BitPermuteStepSimple((ulong)i, 0x5555555555555555UL, 1);
            i = (long)Bits.BitPermuteStepSimple((ulong)i, 0x3333333333333333UL, 2);
            i = (long)Bits.BitPermuteStepSimple((ulong)i, 0x0F0F0F0F0F0F0F0FUL, 4);
            return ReverseBytes(i);
        }

        [CLSCompliantAttribute(false)]
        public static ulong Reverse(ulong i)
        {
            i = Bits.BitPermuteStepSimple(i, 0x5555555555555555UL, 1);
            i = Bits.BitPermuteStepSimple(i, 0x3333333333333333UL, 2);
            i = Bits.BitPermuteStepSimple(i, 0x0F0F0F0F0F0F0F0FUL, 4);
            return ReverseBytes(i);
        }

        public static long ReverseBytes(long i)
        {
            return RotateLeft((long)((ulong)i & 0xFF000000FF000000UL),  8) |
                   RotateLeft((long)((ulong)i & 0x00FF000000FF0000UL), 24) |
                   RotateLeft((long)((ulong)i & 0x0000FF000000FF00UL), 40) |
                   RotateLeft((long)((ulong)i & 0x000000FF000000FFUL), 56);
        }

        [CLSCompliantAttribute(false)]
        public static ulong ReverseBytes(ulong i)
        {
            return RotateLeft(i & 0xFF000000FF000000UL,  8) |
                   RotateLeft(i & 0x00FF000000FF0000UL, 24) |
                   RotateLeft(i & 0x0000FF000000FF00UL, 40) |
                   RotateLeft(i & 0x000000FF000000FFUL, 56);
        }

        public static long RotateLeft(long i, int distance)
        {
            return (i << distance) ^ (long)((ulong)i >> -distance);
        }

        [CLSCompliantAttribute(false)]
        public static ulong RotateLeft(ulong i, int distance)
        {
            return (i << distance) ^ (i >> -distance);
        }

        public static long RotateRight(long i, int distance)
        {
            return (long)((ulong)i >> distance) ^ (i << -distance);
        }

        [CLSCompliantAttribute(false)]
        public static ulong RotateRight(ulong i, int distance)
        {
            return (i >> distance) ^ (i << -distance);
        }
    }
}