From 6de7a04cbd4729bbb0f1ae58f42c948c5e9c7dbc Mon Sep 17 00:00:00 2001 From: crusader Date: Tue, 23 Oct 2018 01:14:52 +0900 Subject: [PATCH] ing --- encoding/binary/binary.go | 68 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 encoding/binary/binary.go diff --git a/encoding/binary/binary.go b/encoding/binary/binary.go new file mode 100644 index 0000000..8e339a8 --- /dev/null +++ b/encoding/binary/binary.go @@ -0,0 +1,68 @@ +package binary + +import ( + "encoding/binary" + "fmt" + "strconv" + "strings" +) + +// StrToBytes converts string("00 00 00 00 00 00 00 00") to []byte +func StrToBytes(str string) []byte { + bytes := make([]byte, 8) + for i, e := range strings.Fields(str) { + b, _ := strconv.ParseUint(e, 16, 64) + bytes[i] = byte(b) + } + return bytes +} + +// BytesToStr converts []byte to string("00 00 00 00 00 00 00 00") +func BytesToStr(bytes ...byte) string { + strs := []string{} + for _, b := range bytes { + strs = append(strs, fmt.Sprintf("%02x", b)) + } + return strings.Join(strs, " ") +} + +// BytesToUInt converts []byte to uint64 +func BytesToUInt(bytes ...byte) uint64 { + padding := make([]byte, 8-len(bytes)) + i := binary.BigEndian.Uint64(append(padding, bytes...)) + return i +} + +// UintToBytes converts uint64 to []byte +func UintToBytes(i uint64, size int) []byte { + bytes := make([]byte, 8) + binary.BigEndian.PutUint64(bytes, i) + return bytes[8-size : 8] +} + +// BytesToInt converts []byte to int64 +func BytesToInt(bytes ...byte) int64 { + if 0x7f < bytes[0] { + mask := uint64(1<