当前位置:网站首页>Go pack and unpack
Go pack and unpack
2022-06-30 06:02:00 【Flower master】
package main
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"math"
"strconv"
"strings"
)
type Protocol struct {
Format []string
}
func main() {
str := "693a0210afc541528457ac135a3fca38"
p := &Protocol{}
s2 := p.HexStringToByte(str)
s1 := p.DecToHexString(s2)
fmt.Println(s1,string(s2),len(s2))
}
// code
func (p *Protocol) Pack(args ...int64) (ret []byte) {
la := len(args)
ls := len(p.Format)
if ls > 0 && la > 0 && ls == la {
for i := 0; i < la; i++ {
if p.Format[i] == "N8" {
ret = append(ret, IntToBytes8(args[i])...)
} else if p.Format[i] == "N4" {
ret = append(ret, IntToBytes4(args[i])...)
} else if p.Format[i] == "N2" {
ret = append(ret, IntToBytes2(args[i])...)
}
}
}
return ret
}
// decode
func (p *Protocol) UnPack(data []byte) []int64 {
la := len(p.Format)
ret := make([]int64, la)
if la > 0 {
for i := 0; i < la; i++ {
if p.Format[i] == "N8" {
ret[i] = Bytes8ToInt64(data[0:8])
data = data[8:]
} else if p.Format[i] == "N4" {
ret[i] = Bytes4ToInt64(data[0:4])
data = data[4:]
} else if p.Format[i] == "N2" {
ret[i] = Bytes2ToInt64(data[0:2])
data = data[2:]
}
}
}
return ret
}
// Turn into 16 Binary coded string
func (p *Protocol) Pack16(args ...int64) (hString string) {
// become byte code
hByte := p.Pack(args...)
// Turn into 16 Base string
hString = p.DecToHexString(hByte)
return hString
}
// decode 16 Base string
func (p *Protocol) UnPack16(hString string) (unIntList []int64) {
HSByte := p.HexStringToByte(hString)
unIntList = p.UnPack(HSByte)
return unIntList
}
//10 Turn into the system 16 Base string
func (p *Protocol) DecToHexString(decString []byte) (responseStr string) {
for _, v := range decString {
hexString := DecHex(int64(v))
if len(hexString) < 2 {
hexString = "0" + hexString
}
responseStr += hexString
}
return strings.ToLower(responseStr)
}
//16 Hexadecimal string to byte type
func (p *Protocol) HexStringToByte(hexString string) (responseByte []byte) {
ls := len(hexString) / 2
for i := 0; i < ls; i++ {
hex := hexString[0:2]
hexString = hexString[2:]
responseByte = append(responseByte, IntToBytes1(HexDec(hex))...)
}
return
}
//int64 turn byte8
func IntToBytes8(n int64) []byte {
var buf = make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(n))
return buf
}
//int64 turn byte4
func IntToBytes4(n int64) []byte {
nb := intToBytes(n, 4)
return nb
}
//int64 turn byte2
func IntToBytes2(n int64) []byte {
nb := intToBytes(n, 2)
return nb
}
//int64 turn byte1
func IntToBytes1(n int64) []byte {
nb := intToBytes(n, 1)
return nb
}
//int64 turn byteN
func intToBytes(n int64, k int) []byte {
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, n)
gbyte := bytesBuffer.Bytes()
//c++ High low conversion
x := len(gbyte)
nb := make([]byte, k)
for i := 0; i < k; i++ {
nb[i] = gbyte[x-i-1]
}
return nb
}
//byte2 turn int64
func Bytes2ToInt64(b []byte) int64 {
nb := []byte{0, 0, b[1], b[0]}
bytesBuffer := bytes.NewBuffer(nb)
var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
return int64(x)
}
//byte4 turn int64
func Bytes4ToInt64(b []byte) int64 {
nb := []byte{b[3], b[2], b[1], b[0]}
bytesBuffer := bytes.NewBuffer(nb)
var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
return int64(x)
}
//byte8 turn int64
func Bytes8ToInt64(buf []byte) int64 {
return int64(binary.BigEndian.Uint64(buf))
}
//10 Base number turn 16 Base number
func DecHex(n int64) string {
if n < 0 {
log.Println("Decimal to hexadecimal error: the argument must be greater than zero.")
return ""
}
if n == 0 {
return "0"
}
hex := map[int64]int64{10: 65, 11: 66, 12: 67, 13: 68, 14: 69, 15: 70}
s := ""
for q := n; q > 0; q = q / 16 {
m := q % 16
if m > 9 && m < 16 {
m = hex[m]
s = fmt.Sprintf("%v%v", string(m), s)
continue
}
s = fmt.Sprintf("%v%v", m, s)
}
return s
}
//16 Base number turn 10 Base number
func HexDec(h string) (n int64) {
s := strings.Split(strings.ToUpper(h), "")
l := len(s)
i := 0
d := float64(0)
hex := map[string]string{"A": "10", "B": "11", "C": "12", "D": "13", "E": "14", "F": "15"}
for i = 0; i < l; i++ {
c := s[i]
if v, ok := hex[c]; ok {
c = v
}
f, err := strconv.ParseFloat(c, 10)
if err != nil {
log.Println("Hexadecimal to decimal error:", err.Error())
return -1
}
d += f * math.Pow(16, float64(l-i-1))
}
return int64(d)
}Reproduced in GO Achieve one PACK and UnPack | Go Technology Forum
边栏推荐
- One sentence introduction to Trojan horse
- 谁不想要一个自己的博客网站呢 - 搭建博客网站wordpress
- 观察者模式、状态模式在实际工作中的使用
- Voting vault: a new primitive for defi and Governance
- Variable parameters of go
- 接口中方法详解
- Gestion des utilisateurs de la base de données MySQL
- 二十四、输入输出设备模型(串口/键盘/磁盘/打印机/总线/中断控制器/DMA和GPU)
- Common mistakes daily practice 01
- UE4_ Editor development: highlight the UI making method according to the assets dragged by the mouse (1)
猜你喜欢
![[ansible series] fundamentals -01](/img/b4/1f3284338c75acb5259849a45bbfbe.jpg)
[ansible series] fundamentals -01

Sword finger offer 22 The penultimate node in the linked list

What indicators should safety service engineers pay attention to in emergency response?
![[GPU] basic operation](/img/76/6b22368e3addd30aef1dd2258ee49a.jpg)
[GPU] basic operation

MySQL存储系统
![[deep learning] data segmentation](/img/16/798881bbee66faa2fb8d9396155010.jpg)
[deep learning] data segmentation

Sound network, standing in the "soil" of the Internet of things

Voting vault: a new primitive for defi and Governance

One sentence introduction to Trojan horse

Huxiaochun came to fengshu electronics to sign a strategic cooperation agreement with Zoomlion
随机推荐
English语法_形容词/副词3级-最高级
Configure the user to log in to the device through telnet -- AAA local authentication
Strlen and sizeof, array length and string length, don't be silly
583. 两个字符串的删除操作-动态规划
Talking about the struct of go
Golang's handwritten Web Framework
After getting these performance test decomposition operations, your test path will be more smooth
Basic operations of C language
At the beginning of 2022, people who are ready to change jobs should pay attention to
What indicators should safety service engineers pay attention to in emergency response?
Sword finger offer 18 Delete the node of the linked list
Go common judgments
Implementation of property management system with ssm+ wechat applet
Detailed explanation of issues related to SSL certificate renewal
Use of tornado template
Leetcode search insert location
Tornado frame foundation
MySQL advanced (Advanced SQL statement)
Gestion des utilisateurs de la base de données MySQL
Ultra simple STM32 RTC alarm clock configuration