mirror of
https://gitee.com/johng/gf
synced 2026-07-08 14:39:50 +08:00
完善gbinary示例
This commit is contained in:
@ -16,7 +16,7 @@ import (
|
||||
// 二进制位(0|1)
|
||||
type Bit uint8
|
||||
|
||||
// (通用,效率较低)二进制打包
|
||||
// 整形二进制打包,注意参数必须为字长确定的类型:int8/16/32/64、uint8/16/32/64
|
||||
func Encode(vs ...interface{}) ([]byte, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
for i := 0; i < len(vs); i++ {
|
||||
@ -28,7 +28,7 @@ func Encode(vs ...interface{}) ([]byte, error) {
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// (通用,效率较低)二进制解包,注意第二个参数之后的变量是变量的指针地址
|
||||
// 整形二进制解包,注意第二个及其后参数为字长确定的整形变量的指针地址,字长确定的类型:int8/16/32/64、uint8/16/32/64
|
||||
func Decode(b []byte, vs ...interface{}) error {
|
||||
buf := bytes.NewBuffer(b)
|
||||
for i := 0; i < len(vs); i++ {
|
||||
|
||||
@ -1 +0,0 @@
|
||||
package gbinary
|
||||
45
geg/encoding/gbinary/binary.go
Normal file
45
geg/encoding/gbinary/binary.go
Normal file
@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"gitee.com/johng/gf/g/encoding/gbinary"
|
||||
"gitee.com/johng/gf/g/os/glog"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 使用gbinary.Encoded对整形二进制打包,注意参数必须为字长确定的类型:int8/16/32/64、uint8/16/32/64
|
||||
if buffer, err := gbinary.Encode(int32(18), int64(24)); err != nil {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
fmt.Println(buffer)
|
||||
}
|
||||
|
||||
|
||||
// 使用gbinary.Decode对整形二进制解包,注意第二个及其后参数为字长确定的整形变量的指针地址,字长确定的类型:int8/16/32/64、uint8/16/32/64
|
||||
if buffer, err := gbinary.Encode(int32(18), int64(24)); err != nil {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
var i1 int32
|
||||
var i2 int64
|
||||
if err := gbinary.Decode(buffer, &i1, &i2); err != nil {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
fmt.Println(i1, i2)
|
||||
}
|
||||
}
|
||||
|
||||
// 编码/解析 int8/16/32/64
|
||||
fmt.Println(gbinary.DecodeToInt8(gbinary.EncodeInt8(int8(100))))
|
||||
fmt.Println(gbinary.DecodeToInt16(gbinary.EncodeInt16(int16(100))))
|
||||
fmt.Println(gbinary.DecodeToInt32(gbinary.EncodeInt32(int32(100))))
|
||||
fmt.Println(gbinary.DecodeToInt64(gbinary.EncodeInt64(int64(100))))
|
||||
|
||||
// 编码/解析 uint8/16/32/64
|
||||
fmt.Println(gbinary.DecodeToUint8(gbinary.EncodeUint8(uint8(100))))
|
||||
fmt.Println(gbinary.DecodeToUint16(gbinary.EncodeUint16(uint16(100))))
|
||||
fmt.Println(gbinary.DecodeToUint32(gbinary.EncodeUint32(uint32(100))))
|
||||
fmt.Println(gbinary.DecodeToUint64(gbinary.EncodeUint64(uint64(100))))
|
||||
|
||||
// 编码/解析 string
|
||||
fmt.Println(gbinary.DecodeToString(gbinary.EncodeString("I'm string!")))
|
||||
}
|
||||
Reference in New Issue
Block a user