github.com/rolandhe/saber@v0.0.4/utils/bytutil/bytesutil.go (about)

     1  // Package bytutil, byte operate tool
     2  //
     3  // Copyright 2023 The saber Authors. All rights reserved.
     4  
     5  package bytutil
     6  
     7  import "errors"
     8  
     9  const mask = 0xff
    10  
    11  // ToInt32 转换4个字节为int32
    12  func ToInt32(buf []byte) (int32, error) {
    13  	if len(buf) < 4 {
    14  		return 0, errors.New("int32 need at least 4 bytes")
    15  	}
    16  	ret := int32(buf[0])
    17  
    18  	ret |= int32(buf[1]) << 8
    19  	ret |= int32(buf[2]) << 16
    20  	ret |= int32(buf[3]) << 24
    21  	return ret, nil
    22  }
    23  
    24  // ToUint32 转换4个字节为uint32
    25  func ToUint32(buf []byte) (uint32, error) {
    26  	ret, err := ToInt32(buf)
    27  	return uint32(ret), err
    28  }
    29  
    30  // ToInt64 转换8个字节为int64
    31  func ToInt64(buf []byte) (int64, error) {
    32  	if len(buf) < 8 {
    33  		return 0, errors.New("int32 need at least 8 bytes")
    34  	}
    35  	ret := int64(buf[0])
    36  
    37  	ret |= int64(buf[1]) << 8
    38  	ret |= int64(buf[2]) << 16
    39  	ret |= int64(buf[3]) << 24
    40  	ret |= int64(buf[4]) << 32
    41  	ret |= int64(buf[5]) << 40
    42  	ret |= int64(buf[6]) << 48
    43  	ret |= int64(buf[7]) << 56
    44  	return ret, nil
    45  }
    46  
    47  // ToUint64 转换8个字节为uit64
    48  func ToUint64(buf []byte) (uint64, error) {
    49  	ret, err := ToInt64(buf)
    50  	return uint64(ret), err
    51  }
    52  
    53  // Int32ToBytes int32 类型值转换为小端的4个字节
    54  func Int32ToBytes(v int32) []byte {
    55  	return Uint32ToBytes(uint32(v))
    56  }
    57  
    58  // Uint32ToBytes uint32 类型值转换为小端的4个字节
    59  func Uint32ToBytes(uv uint32) []byte {
    60  	buf := make([]byte, 4, 4)
    61  	buf[0] = byte(uv & mask)
    62  	buf[1] = byte(uv >> 8 & mask)
    63  	buf[2] = byte(uv >> 16 & mask)
    64  	buf[3] = byte(uv >> 24 & mask)
    65  	return buf
    66  }
    67  
    68  // Int64ToBytes int64类型值转换为小端8个字节
    69  func Int64ToBytes(v int64) []byte {
    70  	return Uint64ToBytes(uint64(v))
    71  }
    72  
    73  // Uint64ToBytes 转换uint64 类型值为小端 8个字节
    74  func Uint64ToBytes(uv uint64) []byte {
    75  	buf := make([]byte, 8)
    76  
    77  	buf[0] = byte(uv & mask)
    78  	buf[1] = byte(uv >> 8 & mask)
    79  	buf[2] = byte(uv >> 16 & mask)
    80  	buf[3] = byte(uv >> 24 & mask)
    81  	buf[4] = byte(uv >> 32 & mask)
    82  	buf[5] = byte(uv >> 40 & mask)
    83  	buf[6] = byte(uv >> 48 & mask)
    84  	buf[7] = byte(uv >> 56 & mask)
    85  
    86  	return buf
    87  }