zoukankan      html  css  js  c++  java
  • 基于GO语言实现的固定长度邀请码

    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
    }
    

      

  • 相关阅读:
    OCP-1Z0-053-V12.02-541题
    OCP-1Z0-053-V12.02-544题
    OCP-1Z0-053-V12.02-545题
    OCP-1Z0-053-V13.02-711题
    OCP-1Z0-053-V12.02-493题
    OCP-1Z0-053-V13.02-696题
    OCP-1Z0-053-V12.02-522题
    OCP-1Z0-053-V12.02-523题
    OCP-1Z0-053-V12.02-534题
    OCP-1Z0-053-V13.02-692题
  • 原文地址:https://www.cnblogs.com/w3liu/p/13881979.html
Copyright © 2011-2022 走看看