OSDN Git Service

versoin1.1.9 (#594)
[bytom/vapor.git] / common / bytes.go
1 // Package common contains various helper functions.
2 package common
3
4 import (
5         "encoding/binary"
6         "encoding/hex"
7 )
8
9 // FromHex convert hex byte string to []byte
10 func FromHex(s string) []byte {
11         if len(s) > 1 {
12                 if s[0:2] == "0x" {
13                         s = s[2:]
14                 }
15                 if len(s)%2 == 1 {
16                         s = "0" + s
17                 }
18                 return Hex2Bytes(s)
19         }
20         return nil
21 }
22
23 // Bytes2Hex convert byte array to string
24 func Bytes2Hex(d []byte) string {
25         return hex.EncodeToString(d)
26 }
27
28 // Hex2Bytes convert hex string to byte array
29 func Hex2Bytes(str string) []byte {
30         h, _ := hex.DecodeString(str)
31         return h
32 }
33
34 // Unit64ToBytes convert uint64 to bytes
35 func Unit64ToBytes(n uint64) []byte {
36         buf := make([]byte, 8)
37         binary.LittleEndian.PutUint64(buf, n)
38         return buf
39 }
40
41 // BytesToUnit64 convert bytes to uint64
42 func BytesToUnit64(b []byte) uint64 {
43         return binary.LittleEndian.Uint64(b)
44 }