zigzag.go 1020 B

1234567891011121314151617181920212223242526272829303132
  1. // Copyright 2011 The Snappy-Go Authors. 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 zigzag implements the zigzag mapping between signed and unsigned
  5. // integers:
  6. // +0 <-> 0
  7. // -1 <-> 1
  8. // +1 <-> 2
  9. // -2 <-> 3
  10. // +2 <-> 4
  11. // etcetera
  12. //
  13. // It is the same format used by protocol buffers. The format is described at
  14. // http://code.google.com/apis/protocolbuffers/docs/encoding.html
  15. package zigzag
  16. // Itou64 maps a signed integer to an unsigned integer.
  17. // If i >= 0, the result is 2*i.
  18. // If i < 0, the result is -2*i - 1.
  19. // The formulae above are in terms of ideal integers, with no overflow.
  20. func Itou64(i int64) uint64 {
  21. return uint64(i<<1 ^ i>>63)
  22. }
  23. // Utoi64 maps an unsigned integer to a signed integer.
  24. // If u%2 == 0, the result is u/2.
  25. // If u%2 == 1, the result is -(u+1)/2.
  26. // The formulae above are in terms of ideal integers, with no overflow.
  27. func Utoi64(u uint64) int64 {
  28. return int64(u>>1) ^ -int64(u&1)
  29. }