github.com/chain5j/chain5j-pkg@v1.0.7/util/hexutil/bytes.go (about)

     1  // Package hexutil
     2  //
     3  // @author: xwc1125
     4  package hexutil
     5  
     6  import "encoding/hex"
     7  
     8  // FromHex returns the bytes represented by the hexadecimal string s.
     9  // s may be prefixed with "0x".
    10  func FromHex(s string) []byte {
    11  	if len(s) > 1 {
    12  		if s[0:2] == "0x" || s[0:2] == "0X" {
    13  			s = s[2:]
    14  		}
    15  	}
    16  	if len(s)%2 == 1 {
    17  		s = "0" + s
    18  	}
    19  	return Hex2Bytes(s)
    20  }
    21  
    22  // Bytes2Hex returns the hexadecimal encoding of d.
    23  func Bytes2Hex(d []byte) string {
    24  	return Encode(d)
    25  }
    26  
    27  // Hex2Bytes returns the bytes represented by the hexadecimal string str.
    28  func Hex2Bytes(str string) []byte {
    29  	h, _ := Decode(str)
    30  	return h
    31  }
    32  
    33  // Hex2BytesFixed returns bytes of a specified fixed length flen.
    34  func Hex2BytesFixed(str string, flen int) []byte {
    35  	h, _ := hex.DecodeString(str)
    36  	if len(h) == flen {
    37  		return h
    38  	}
    39  	if len(h) > flen {
    40  		return h[len(h)-flen:]
    41  	}
    42  	hh := make([]byte, flen)
    43  	copy(hh[flen-len(h):flen], h)
    44  	return hh
    45  }
    46  
    47  // CopyBytes returns an exact copy of the provided bytes.
    48  func CopyBytes(b []byte) (copiedBytes []byte) {
    49  	if b == nil {
    50  		return nil
    51  	}
    52  	copiedBytes = make([]byte, len(b))
    53  	copy(copiedBytes, b)
    54  
    55  	return
    56  }
    57  
    58  // RightPadBytes zero-pads slice to the right up to length l.
    59  func RightPadBytes(slice []byte, l int) []byte {
    60  	if l <= len(slice) {
    61  		return slice
    62  	}
    63  
    64  	padded := make([]byte, l)
    65  	copy(padded, slice)
    66  
    67  	return padded
    68  }
    69  
    70  // LeftPadBytes zero-pads slice to the left up to length l.
    71  func LeftPadBytes(slice []byte, l int) []byte {
    72  	if l <= len(slice) {
    73  		return slice
    74  	}
    75  
    76  	padded := make([]byte, l)
    77  	copy(padded[l-len(slice):], slice)
    78  
    79  	return padded
    80  }
    81  
    82  // TrimLeftZeroes returns a subslice of s without leading zeroes
    83  func TrimLeftZeroes(s []byte) []byte {
    84  	idx := 0
    85  	for ; idx < len(s); idx++ {
    86  		if s[idx] != 0 {
    87  			break
    88  		}
    89  	}
    90  	return s[idx:]
    91  }