github.com/godaddy-x/freego@v1.0.156/utils/reflect_value.go (about) 1 package utils 2 3 import ( 4 "strconv" 5 "unsafe" 6 ) 7 8 // byte to string 9 func NewString(b []byte) (string, error) { 10 return *((*string)(unsafe.Pointer(&b))), nil 11 } 12 13 // byte to int 14 func NewInt(b []byte) (int, error) { 15 if ret, err := NewInt64(b); err != nil { 16 return 0, err 17 } else { 18 return int(ret), nil 19 } 20 } 21 22 // byte to int8 23 func NewInt8(b []byte) (int8, error) { 24 if ret, err := NewInt64(b); err != nil { 25 return 0, err 26 } else { 27 return int8(ret), nil 28 } 29 } 30 31 // byte to int16 32 func NewInt16(b []byte) (int16, error) { 33 if ret, err := NewInt64(b); err != nil { 34 return 0, err 35 } else { 36 return int16(ret), nil 37 } 38 } 39 40 // byte to int32 41 func NewInt32(b []byte) (int32, error) { 42 if ret, err := NewInt64(b); err != nil { 43 return 0, err 44 } else { 45 return int32(ret), nil 46 } 47 } 48 49 // byte to int64 50 func NewInt64(b []byte) (int64, error) { 51 str, _ := NewString(b) 52 if i64, err := strconv.ParseInt(str, 10, 64); err != nil { 53 return 0, err 54 } else { 55 return i64, nil 56 } 57 } 58 59 // byte to float32 60 func NewFloat32(b []byte) (float32, error) { 61 if ret, err := NewFloat64(b); err != nil { 62 return 0, err 63 } else { 64 return float32(ret), nil 65 } 66 } 67 68 // byte to float64 69 func NewFloat64(b []byte) (float64, error) { 70 str, _ := NewString(b) 71 f64, err := strconv.ParseFloat(str, 64) 72 if err != nil { 73 return 0, err 74 } 75 return f64, nil 76 } 77 78 // byte to uint 79 func NewUint(b []byte) (uint, error) { 80 if ret, err := NewInt64(b); err != nil { 81 return 0, err 82 } else { 83 return uint(ret), err 84 } 85 } 86 87 // byte to uint8 88 func NewUint8(b []byte) (uint8, error) { 89 if ret, err := NewInt64(b); err != nil { 90 return 0, err 91 } else { 92 return uint8(ret), err 93 } 94 } 95 96 // byte to uint16 97 func NewUint16(b []byte) (uint16, error) { 98 if ret, err := NewInt64(b); err != nil { 99 return 0, err 100 } else { 101 return uint16(ret), err 102 } 103 } 104 105 // byte to uint32 106 func NewUint32(b []byte) (uint32, error) { 107 if ret, err := NewInt64(b); err != nil { 108 return 0, err 109 } else { 110 return uint32(ret), err 111 } 112 } 113 114 // byte to uint64 115 func NewUint64(b []byte) (uint64, error) { 116 if ret, err := NewInt64(b); err != nil { 117 return 0, err 118 } else { 119 return uint64(ret), err 120 } 121 }