int16_16.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright ©2021 The star-tex 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-STAR-TEX file.
  4. package fixed
  5. import (
  6. "fmt"
  7. "strconv"
  8. )
  9. // Int16_16 is a signed 16.16 fixed-point number.
  10. //
  11. // The integer part ranges from -32768 to 32767, inclusive. The
  12. // fractional part has 20 bits of precision.
  13. type Int16_16 uint32
  14. // I16_16 returns the integer value i as an Int16_16.
  15. //
  16. // For example, passing the integer value 2 yields Int16_16(131072).
  17. func I16_16(v int) Int16_16 {
  18. return Int16_16(v << 16)
  19. }
  20. // ParseInt16_16 converts the string s to a signed 16.16 fixed-point number.
  21. func ParseInt16_16(s string) (Int16_16, error) {
  22. f, err := strconv.ParseFloat(s, 32)
  23. if err != nil {
  24. return 0, err
  25. }
  26. return Int16_16(int(f * (1 << 16))), nil
  27. }
  28. func (x Int16_16) Float64() float64 {
  29. v := int32(x)
  30. return float64(v) / (1 << 16)
  31. }
  32. // String returns a human-readable representation of a 16.16 fixed-point number.
  33. func (x Int16_16) String() string {
  34. const (
  35. shift = 16
  36. mask = 1<<shift - 1
  37. )
  38. if x >= 0 {
  39. return fmt.Sprintf("%d:%02d", int32(x>>shift), int32(x&mask))
  40. }
  41. x = -x
  42. if x >= 0 {
  43. return fmt.Sprintf("-%d:%02d", int32(x>>shift), int32(x&mask))
  44. }
  45. return "-32768:00" // The minimum value is -(1<<(16-1)).
  46. }