This commit is contained in:
crusader 2018-10-23 10:53:58 +09:00
parent 6de7a04cbd
commit 7ca2a3f245

View File

@ -1,68 +0,0 @@
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<<uint(len(bytes)*8-1) - 1)
bytes[0] &= 0x7f
i := BytesToUInt(bytes...)
i = (^i + 1) & mask
return int64(-i)
} else {
i := BytesToUInt(bytes...)
return int64(i)
}
}
// IntToBytes converts int to []byte
func IntToBytes(i int, size int) []byte {
var ui uint64
if 0 < i {
ui = uint64(i)
} else {
ui = (^uint64(-i) + 1)
}
return UintToBytes(ui, size)
}