bitops.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2014-2022 Ulrich Kunitz. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package lzma
  5. /* Naming conventions follows the CodeReviewComments in the Go Wiki. */
  6. // ntz32Const is used by the functions NTZ and NLZ.
  7. const ntz32Const = 0x04d7651f
  8. // ntz32Table is a helper table for de Bruijn algorithm by Danny Dubé.
  9. // See Henry S. Warren, Jr. "Hacker's Delight" section 5-1 figure 5-26.
  10. var ntz32Table = [32]int8{
  11. 0, 1, 2, 24, 3, 19, 6, 25,
  12. 22, 4, 20, 10, 16, 7, 12, 26,
  13. 31, 23, 18, 5, 21, 9, 15, 11,
  14. 30, 17, 8, 14, 29, 13, 28, 27,
  15. }
  16. /*
  17. // ntz32 computes the number of trailing zeros for an unsigned 32-bit integer.
  18. func ntz32(x uint32) int {
  19. if x == 0 {
  20. return 32
  21. }
  22. x = (x & -x) * ntz32Const
  23. return int(ntz32Table[x>>27])
  24. }
  25. */
  26. // nlz32 computes the number of leading zeros for an unsigned 32-bit integer.
  27. func nlz32(x uint32) int {
  28. // Smear left most bit to the right
  29. x |= x >> 1
  30. x |= x >> 2
  31. x |= x >> 4
  32. x |= x >> 8
  33. x |= x >> 16
  34. // Use ntz mechanism to calculate nlz.
  35. x++
  36. if x == 0 {
  37. return 0
  38. }
  39. x *= ntz32Const
  40. return 32 - int(ntz32Table[x>>27])
  41. }