当前位置:网站首页>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
边栏推荐
- Mysql database user management
- Master slave synchronization of MySQL database to realize read-write separation
- Golang之手写web框架
- How to automatically renew a token after it expires?
- Acwing winter vacation daily question 2022 punch in day 11
- CompletionService使用及原理(源码分析)
- The average salary of software testing in 2022 has been released. Have you been averaged?
- 1380. lucky numbers in matrices
- InputStream转InputStreamSource
- 【学习强化学习】总目录
猜你喜欢

Sword finger offer 18 Delete the node of the linked list

Golang之手写web框架

PC viewing WiFi password

inno setup 最简单的自定义界面效果

Did you know that WPS can turn on eye protection mode?
![[deep learning] data segmentation](/img/16/798881bbee66faa2fb8d9396155010.jpg)
[deep learning] data segmentation

Master slave synchronization of MySQL database to realize read-write separation

谁不想要一个自己的博客网站呢 - 搭建博客网站wordpress

Basic operations of C language

Idea of capturing mobile terminal variant combination
随机推荐
MySQL advanced (Advanced SQL statement)
Dao -- a beautiful new world?
[regular expression series] greedy and non greedy patterns
Network basics
Sword finger offer 22 The penultimate node in the linked list
Navigate back to fragmentpageradapter - & gt; Fragment is empty - navigating back to fragmentpageradapter - & gt; fragments are empty
Dynamic programming -- gliding wing of the strange thief Kidd
CompletableFuture从了解到精通,你想知道的这里都有
Develop stylelint rules from zero (plug-ins)
网络基础知识
Golang's handwritten Web Framework
Learning automation ppt
Did you know that WPS can turn on eye protection mode?
Potential bottleneck of redis
MySQL日志管理、数据备份、恢复
InputStream to inputstreamsource
OSPF - authentication and load balancing summary (including configuration commands)
拼多多店铺搜索相关问题,为什么新品上架搜索不到
Balanced binary tree judgment of Li Kou 110 -- classic problems
谁不想要一个自己的博客网站呢 - 搭建博客网站wordpress