1 Star 1 Fork 0

iceinto / ipkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
int.go 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
package iconv
import (
"gitee.com/iceinto/ipkg/ibinary"
"strconv"
)
// Int converts `any` to int.
func Int(any interface{}) int {
if any == nil {
return 0
}
if v, ok := any.(int); ok {
return v
}
return int(Int64(any))
}
// Int8 converts `any` to int8.
func Int8(any interface{}) int8 {
if any == nil {
return 0
}
if v, ok := any.(int8); ok {
return v
}
return int8(Int64(any))
}
// Int16 converts `any` to int16.
func Int16(any interface{}) int16 {
if any == nil {
return 0
}
if v, ok := any.(int16); ok {
return v
}
return int16(Int64(any))
}
// Int32 converts `any` to int32.
func Int32(any interface{}) int32 {
if any == nil {
return 0
}
if v, ok := any.(int32); ok {
return v
}
return int32(Int64(any))
}
// Int64 converts `any` to int64.
func Int64(any interface{}) int64 {
if any == nil {
return 0
}
switch value := any.(type) {
case int:
return int64(value)
case int8:
return int64(value)
case int16:
return int64(value)
case int32:
return int64(value)
case int64:
return value
case uint:
return int64(value)
case uint8:
return int64(value)
case uint16:
return int64(value)
case uint32:
return int64(value)
case uint64:
return int64(value)
case float32:
return int64(value)
case float64:
return int64(value)
case bool:
if value {
return 1
}
return 0
case []byte:
return ibinary.DecodeToInt64(value)
default:
s := String(value)
isMinus := false
if len(s) > 0 {
if s[0] == '-' {
isMinus = true
s = s[1:]
} else if s[0] == '+' {
s = s[1:]
}
}
// Hexadecimal
if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
if v, e := strconv.ParseInt(s[2:], 16, 64); e == nil {
if isMinus {
return -v
}
return v
}
}
// Octal
if len(s) > 1 && s[0] == '0' {
if v, e := strconv.ParseInt(s[1:], 8, 64); e == nil {
if isMinus {
return -v
}
return v
}
}
// Decimal
if v, e := strconv.ParseInt(s, 10, 64); e == nil {
if isMinus {
return -v
}
return v
}
// Float64
return int64(Float64(value))
}
}
1
https://gitee.com/iceinto/ipkg.git
git@gitee.com:iceinto/ipkg.git
iceinto
ipkg
ipkg
v1.0.2

搜索帮助