gconv_uint.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gconv
  7. import (
  8. "math"
  9. "strconv"
  10. "github.com/gogf/gf/v2/encoding/gbinary"
  11. )
  12. // Uint converts `any` to uint.
  13. func Uint(any interface{}) uint {
  14. if any == nil {
  15. return 0
  16. }
  17. if v, ok := any.(uint); ok {
  18. return v
  19. }
  20. return uint(Uint64(any))
  21. }
  22. // Uint8 converts `any` to uint8.
  23. func Uint8(any interface{}) uint8 {
  24. if any == nil {
  25. return 0
  26. }
  27. if v, ok := any.(uint8); ok {
  28. return v
  29. }
  30. return uint8(Uint64(any))
  31. }
  32. // Uint16 converts `any` to uint16.
  33. func Uint16(any interface{}) uint16 {
  34. if any == nil {
  35. return 0
  36. }
  37. if v, ok := any.(uint16); ok {
  38. return v
  39. }
  40. return uint16(Uint64(any))
  41. }
  42. // Uint32 converts `any` to uint32.
  43. func Uint32(any interface{}) uint32 {
  44. if any == nil {
  45. return 0
  46. }
  47. if v, ok := any.(uint32); ok {
  48. return v
  49. }
  50. return uint32(Uint64(any))
  51. }
  52. // Uint64 converts `any` to uint64.
  53. func Uint64(any interface{}) uint64 {
  54. if any == nil {
  55. return 0
  56. }
  57. switch value := any.(type) {
  58. case int:
  59. return uint64(value)
  60. case int8:
  61. return uint64(value)
  62. case int16:
  63. return uint64(value)
  64. case int32:
  65. return uint64(value)
  66. case int64:
  67. return uint64(value)
  68. case uint:
  69. return uint64(value)
  70. case uint8:
  71. return uint64(value)
  72. case uint16:
  73. return uint64(value)
  74. case uint32:
  75. return uint64(value)
  76. case uint64:
  77. return value
  78. case float32:
  79. return uint64(value)
  80. case float64:
  81. return uint64(value)
  82. case bool:
  83. if value {
  84. return 1
  85. }
  86. return 0
  87. case []byte:
  88. return gbinary.DecodeToUint64(value)
  89. default:
  90. if f, ok := value.(iUint64); ok {
  91. return f.Uint64()
  92. }
  93. s := String(value)
  94. // Hexadecimal
  95. if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
  96. if v, e := strconv.ParseUint(s[2:], 16, 64); e == nil {
  97. return v
  98. }
  99. }
  100. // Decimal
  101. if v, e := strconv.ParseUint(s, 10, 64); e == nil {
  102. return v
  103. }
  104. // Float64
  105. if valueFloat64 := Float64(value); math.IsNaN(valueFloat64) {
  106. return 0
  107. } else {
  108. return uint64(valueFloat64)
  109. }
  110. }
  111. }