Files
zogo/examples/bytepacket/main.go
T
4566704 f9f7c7c92f feat(bytepacket): 自 go-hua 迁入二进制封包工具
- 小端序读写, 兼容易语言协议(GBK 字符串/易语言日期)
- 附测试、examples/bytepacket 例程与包 README
2026-09-20 12:25:35 +08:00

44 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// bytepacket 包示例:二进制封包/解包(小端序,兼容易语言协议,含 GBK 字符串与易语言日期)
package main
import (
"fmt"
"git.zeroonesoft.cn/golib/zogo/bytepacket"
)
func main() {
// ===== 写入封包 =====
p := bytepacket.NewPacket(nil)
p.WriteInt32(100)
p.WriteUInt16(200)
_ = p.WriteString("hello")
_ = p.WriteStringGbk("中文GBK")
_ = p.WriteBytes([]byte{1, 2, 3})
data := p.GetData()
fmt.Printf("封包总长: %d 字节\n", len(data))
// ===== 读取封包(按写入顺序读出)=====
r := bytepacket.NewPacket(data)
fmt.Println("ReadInt32:", r.ReadInt32())
fmt.Println("ReadUInt16:", r.ReadUInt16())
s, _ := r.ReadString()
fmt.Println("ReadString:", s)
gbk, _ := r.ReadStringGbk()
fmt.Println("ReadStringGbk:", gbk)
fmt.Println("ReadBytes:", r.ReadBytes())
// ===== GBK / UTF-8 互转 =====
gbkBytes, _ := bytepacket.Utf8ToGbk([]byte("编码转换"))
fmt.Printf("UTF-8→GBK: % X\n", gbkBytes)
utf8Bytes, _ := bytepacket.GbkToUtf8(gbkBytes)
fmt.Println("GBK→UTF-8:", string(utf8Bytes))
// ===== 易语言日期时间(float64 天数,起点 1899-12-30)=====
d := bytepacket.NewPacket(nil)
d.WriteFloat64(45292.5) // ≈ 2024-01-01 12:00:00
t := d.ReadElangDateTime()
fmt.Println("ReadElangDateTime:", t.Format("2006-01-02 15:04:05"))
}