feat: byte utils

This commit is contained in:
tx7do
2023-10-28 20:06:50 +08:00
parent b4188ca4d8
commit 82fbdc15d9
8 changed files with 98 additions and 1 deletions

44
byteutil/util.go Normal file
View File

@@ -0,0 +1,44 @@
package byteutil
import (
"bytes"
"encoding/binary"
)
// IntToBytes 将int转换为[]byte
func IntToBytes(n int) []byte {
data := int64(n)
byteBuf := bytes.NewBuffer([]byte{})
_ = binary.Write(byteBuf, binary.BigEndian, data)
return byteBuf.Bytes()
}
// BytesToInt 将[]byte转换为int
func BytesToInt(bys []byte) int {
byteBuf := bytes.NewBuffer(bys)
var data int64
_ = binary.Read(byteBuf, binary.BigEndian, &data)
return int(data)
}
// ByteToLower lowers a byte
func ByteToLower(b byte) byte {
if b <= '\u007F' {
if 'A' <= b && b <= 'Z' {
b += 'a' - 'A'
}
return b
}
return b
}
// ByteToUpper upper a byte
func ByteToUpper(b byte) byte {
if b <= '\u007F' {
if 'a' <= b && b <= 'z' {
b -= 'a' - 'A'
}
return b
}
return b
}

11
byteutil/util_test.go Normal file
View File

@@ -0,0 +1,11 @@
package byteutil
import (
"fmt"
"testing"
)
func TestIntToBytes(t *testing.T) {
fmt.Println(IntToBytes(1))
fmt.Println(BytesToInt(IntToBytes(1)))
}