Longs.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
  6. {
  7. public abstract class Longs
  8. {
  9. public const int NumBits = 64;
  10. public const int NumBytes = 8;
  11. private static readonly byte[] DeBruijnTZ = {
  12. 0x3F, 0x00, 0x01, 0x34, 0x02, 0x06, 0x35, 0x1A, 0x03, 0x25, 0x28, 0x07, 0x21, 0x36, 0x2F, 0x1B,
  13. 0x3D, 0x04, 0x26, 0x2D, 0x2B, 0x29, 0x15, 0x08, 0x17, 0x22, 0x3A, 0x37, 0x30, 0x11, 0x1C, 0x0A,
  14. 0x3E, 0x33, 0x05, 0x19, 0x24, 0x27, 0x20, 0x2E, 0x3C, 0x2C, 0x2A, 0x14, 0x16, 0x39, 0x10, 0x09,
  15. 0x32, 0x18, 0x23, 0x1F, 0x3B, 0x13, 0x38, 0x0F, 0x31, 0x1E, 0x12, 0x0E, 0x1D, 0x0D, 0x0C, 0x0B };
  16. public static int NumberOfLeadingZeros(long i)
  17. {
  18. int x = (int)(i >> 32), n = 0;
  19. if (x == 0)
  20. {
  21. n = 32;
  22. x = (int)i;
  23. }
  24. return n + Integers.NumberOfLeadingZeros(x);
  25. }
  26. public static int NumberOfTrailingZeros(long i)
  27. {
  28. int n = DeBruijnTZ[(uint)((ulong)((i & -i) * 0x045FBAC7992A70DAL) >> 58)];
  29. long m = (((i & 0xFFFFFFFFL) | (long)((ulong)i >> 32)) - 1L) >> 63;
  30. return n - (int)m;
  31. }
  32. public static long Reverse(long i)
  33. {
  34. return (long)Reverse((ulong)i);
  35. }
  36. public static ulong Reverse(ulong i)
  37. {
  38. i = Bits.BitPermuteStepSimple(i, 0x5555555555555555UL, 1);
  39. i = Bits.BitPermuteStepSimple(i, 0x3333333333333333UL, 2);
  40. i = Bits.BitPermuteStepSimple(i, 0x0F0F0F0F0F0F0F0FUL, 4);
  41. return ReverseBytes(i);
  42. }
  43. public static long ReverseBytes(long i)
  44. {
  45. return (long)ReverseBytes((ulong)i);
  46. }
  47. public static ulong ReverseBytes(ulong i)
  48. {
  49. return RotateLeft(i & 0xFF000000FF000000UL, 8) |
  50. RotateLeft(i & 0x00FF000000FF0000UL, 24) |
  51. RotateLeft(i & 0x0000FF000000FF00UL, 40) |
  52. RotateLeft(i & 0x000000FF000000FFUL, 56);
  53. }
  54. public static long RotateLeft(long i, int distance)
  55. {
  56. return (i << distance) ^ (long)((ulong)i >> -distance);
  57. }
  58. public static ulong RotateLeft(ulong i, int distance)
  59. {
  60. return (i << distance) ^ (i >> -distance);
  61. }
  62. public static long RotateRight(long i, int distance)
  63. {
  64. return (long)((ulong)i >> distance) ^ (i << -distance);
  65. }
  66. public static ulong RotateRight(ulong i, int distance)
  67. {
  68. return (i >> distance) ^ (i << -distance);
  69. }
  70. }
  71. }
  72. #pragma warning restore
  73. #endif