github.com/sandwich-go/boost@v1.3.29/xconv/int.go (about) 1 package xconv 2 3 import ( 4 "strconv" 5 ) 6 7 // Int converts `any` to int. 8 func Int(any interface{}) int { 9 if any == nil { 10 return 0 11 } 12 if v, ok := any.(int); ok { 13 return v 14 } 15 return int(Int64(any)) 16 } 17 18 // Int8 converts `any` to int8. 19 func Int8(any interface{}) int8 { 20 if any == nil { 21 return 0 22 } 23 if v, ok := any.(int8); ok { 24 return v 25 } 26 return int8(Int64(any)) 27 } 28 29 // Int16 converts `any` to int16. 30 func Int16(any interface{}) int16 { 31 if any == nil { 32 return 0 33 } 34 if v, ok := any.(int16); ok { 35 return v 36 } 37 return int16(Int64(any)) 38 } 39 40 // Int32 [影响性能] converts `any` to int32. 41 func Int32(any interface{}) int32 { 42 if any == nil { 43 return 0 44 } 45 if v, ok := any.(int32); ok { 46 return v 47 } 48 return int32(Int64(any)) 49 } 50 51 // Int64 converts `any` to int64. 52 func Int64(any interface{}) int64 { 53 if any == nil { 54 return 0 55 } 56 switch value := any.(type) { 57 case int: 58 return int64(value) 59 case int8: 60 return int64(value) 61 case int16: 62 return int64(value) 63 case int32: 64 return int64(value) 65 case int64: 66 return value 67 case uint: 68 return int64(value) 69 case uint8: 70 return int64(value) 71 case uint16: 72 return int64(value) 73 case uint32: 74 return int64(value) 75 case uint64: 76 return int64(value) 77 case float32: 78 return int64(value) 79 case float64: 80 return int64(value) 81 case bool: 82 if value { 83 return 1 84 } 85 return 0 86 case []byte: 87 return LittleEndianDecodeToInt64(value) 88 default: 89 if f, ok := value.(iInt64); ok { 90 return f.Int64() 91 } 92 s := String(value) 93 isMinus := false 94 if len(s) > 0 { 95 if s[0] == '-' { 96 isMinus = true 97 s = s[1:] 98 } else if s[0] == '+' { 99 s = s[1:] 100 } 101 } 102 // Hexadecimal 103 if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') { 104 if v, e := strconv.ParseInt(s[2:], 16, 64); e == nil { 105 if isMinus { 106 return -v 107 } 108 return v 109 } 110 } 111 // Octal 112 if len(s) > 1 && s[0] == '0' { 113 if v, e := strconv.ParseInt(s[1:], 8, 64); e == nil { 114 if isMinus { 115 return -v 116 } 117 return v 118 } 119 } 120 // Decimal 121 if v, e := strconv.ParseInt(s, 10, 64); e == nil { 122 if isMinus { 123 return -v 124 } 125 return v 126 } 127 // Float64 128 return int64(Float64(value)) 129 } 130 } 131 132 // LeFillUpSize 当b位数不够时,进行高位补0。 133 // 注意这里为了不影响原有输入参数,是采用的值复制设计。 134 func LeFillUpSize(b []byte, l int) []byte { 135 if len(b) >= l { 136 return b[:l] 137 } 138 c := make([]byte, l) 139 copy(c, b) 140 return c 141 }