github.com/orangebees/go-oneutils@v0.0.10/Convert/func.go (about)

     1  package Convert
     2  
     3  import (
     4  	"math"
     5  	"strings"
     6  	"unsafe"
     7  )
     8  
     9  const hextable = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    10  
    11  // S2B string转[]byte
    12  func S2B(s string) (b []byte) {
    13  	*(*string)(unsafe.Pointer(&b)) = s
    14  	*(*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&b)) + 2*unsafe.Sizeof(&b))) = len(s)
    15  	return
    16  }
    17  
    18  // B2S []byte转string
    19  func B2S(b []byte) string {
    20  	return *(*string)(unsafe.Pointer(&b))
    21  }
    22  
    23  // Uint64ToBase62Bytes uint转62进制字节数组
    24  func Uint64ToBase62Bytes(num uint64) []byte {
    25  	var bytes = make([]byte, 11)
    26  	bytes = bytes[:0]
    27  	for num > 0 {
    28  		bytes = append(bytes, hextable[num%62])
    29  		num = num / 62
    30  	}
    31  	for left, right := 0, len(bytes)-1; left < right; left, right = left+1, right-1 {
    32  		bytes[left], bytes[right] = bytes[right], bytes[left]
    33  	}
    34  	return bytes
    35  }
    36  
    37  // Base62BytesToUint64 62进制字节数组转uint64
    38  func Base62BytesToUint64(str []byte) uint64 {
    39  	var num uint64
    40  	n := len(str)
    41  	for i := 0; i < n; i++ {
    42  		pos := strings.IndexByte(hextable, str[i])
    43  		num += uint64(math.Pow(62, float64(n-i-1)) * float64(pos))
    44  	}
    45  	return num
    46  }