PowerOf2.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. namespace MongoDB.Bson
  17. {
  18. internal static class PowerOf2
  19. {
  20. public static bool IsPowerOf2(int n)
  21. {
  22. if (n < 0 || n > 0x40000000)
  23. {
  24. throw new ArgumentOutOfRangeException(nameof(n));
  25. }
  26. var result = (n & (n - 1)) == 0;
  27. return result;
  28. }
  29. public static int RoundUpToPowerOf2(int n)
  30. {
  31. if (IsPowerOf2(n))
  32. {
  33. return n;
  34. }
  35. // see: Hacker's Delight, by Henry S. Warren
  36. n = n - 1;
  37. n = n | (n >> 1);
  38. n = n | (n >> 2);
  39. n = n | (n >> 4);
  40. n = n | (n >> 8);
  41. n = n | (n >> 16);
  42. return n + 1;
  43. }
  44. }
  45. }