1. 選取數字加英文字母組成32個字符的字符串,用於表示32進制數。
2. 用一個特定的字符比如`G`作為分隔符,解析的時候字符`G`后面的字符不參與運算。
3. LEN表示邀請碼長度,默認為6。
github鏈接:https://github.com/w3liu/go-common/tree/master/invitecode
代碼如下:
package invitecode import ( "strings" ) const ( BASE = "E8S2DZX9WYLTN6BQF7CP5IK3MJUAR4HV" DECIMAL = 32 PAD = "G" LEN = 6 ) // id轉code func Encode(uid uint64) string { id := uid mod := uint64(0) res := "" for id != 0 { mod = id % DECIMAL id = id / DECIMAL res += string(BASE[mod]) } resLen := len(res) if resLen < LEN { res += PAD for i := 0; i < LEN-resLen-1; i++ { res += string(BASE[(int(uid)+i)%DECIMAL]) } } return res } func Decode(code string) uint64 { res := uint64(0) lenCode := len(code) baseArr := []byte(BASE) // 字符串進制轉換為byte數組 baseRev := make(map[byte]int) // 進制數據鍵值轉換為map for k, v := range baseArr { baseRev[v] = k } // 查找補位字符的位置 isPad := strings.Index(code, PAD) if isPad != -1 { lenCode = isPad } r := 0 for i := 0; i < lenCode; i++ { // 補充字符直接跳過 if string(code[i]) == PAD { continue } index, ok := baseRev[code[i]] if !ok { return 0 } b := uint64(1) for j := 0; j < r; j++ { b *= DECIMAL } res += uint64(index) * b r++ } return res }