1 Star 0 Fork 0

vitarch / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
numeric.go 1.90 KB
一键复制 编辑 原始数据 按行查看 历史
vitarch 提交于 2023-06-15 11:14 . init
package utilsConvert
import (
"bytes"
"encoding/binary"
"reflect"
"strconv"
)
// ToInt 转int
func ToInt(src interface{}) int {
var dst int
val := reflect.ValueOf(src)
switch src.(type) {
case int, int8, int16, int32, int64:
dst = int(val.Int())
case uint, uint8, uint16, uint32, uint64:
dst = int(val.Uint())
case float32, float64:
dst = int(val.Float())
case string:
if len(val.String()) == 0 {
return 0
}
dst, _ = strconv.Atoi(val.String())
default:
dst = int(-1)
}
return dst
}
// ToInt64 转int64
func ToInt64(src interface{}) int64 {
var dst int64
val := reflect.ValueOf(src)
switch src.(type) {
case int, int8, int16, int32, int64:
dst = val.Int()
case uint, uint8, uint16, uint32, uint64:
dst = int64(val.Uint())
case float32, float64:
dst = int64(val.Float())
case string:
if len(val.String()) == 0 {
return int64(0)
}
dst, _ = strconv.ParseInt(val.String(), 10, 64)
default:
dst = int64(-1)
}
return dst
}
// ToFloat64 转float64
func ToFloat64(src interface{}) float64 {
var dst float64
val := reflect.ValueOf(src)
switch src.(type) {
case int, int8, int16, int32, int64:
dst = float64(val.Int())
case uint, uint8, uint16, uint32, uint64:
dst = float64(val.Uint())
case float64, float32:
dst = val.Float()
case string:
if len(val.String()) == 0 {
return float64(0)
}
dst, _ = strconv.ParseFloat(val.String(), 64)
default:
dst = float64(-1)
}
return dst
}
func IntToBitBytes(n int, length int) []byte {
switch length {
case 32:
data := int32(n)
bytebuf := bytes.NewBuffer([]byte{})
binary.Write(bytebuf, binary.BigEndian, data)
return bytebuf.Bytes()
case 64:
data := int64(n)
bytebuf := bytes.NewBuffer([]byte{})
binary.Write(bytebuf, binary.BigEndian, data)
return bytebuf.Bytes()
default:
data := int32(n)
bytebuf := bytes.NewBuffer([]byte{})
binary.Write(bytebuf, binary.BigEndian, data)
return bytebuf.Bytes()
}
}
Go
1
https://gitee.com/vitarch/goutils.git
git@gitee.com:vitarch/goutils.git
vitarch
goutils
goutils
7ec6a993d123

搜索帮助