TLDR
在大多数情况下,最好在内部处理数字并在外部将它们编码为短 ID。所以这里有一个用于Python3、PowerShell 和VBA 的函数,它将一个int32 转换为一个字母数字ID。像这样使用它:
int32_to_id(225204568)
'F2AXP8'
对于分布式代码,请使用 ULID:https://github.com/mdipierro/ulid
它们更长,但在不同的机器上是独一无二的。
ID 有多短?
它将用 6 个字符编码大约十亿个 ID,因此它尽可能紧凑,同时仍然只使用 non-ambiguous digits and letters。
如何获得更短的 ID?
如果您想要更紧凑的 ID/代码/序列号,只需更改 chars="..." 定义即可轻松扩展字符集。例如,如果您允许所有小写和大写字母,您可以在相同的 6 个字符内拥有 560 亿个 ID。添加一些符号(如~!@#$%^&*()_+-=)会为您提供 2080 亿个 ID。
那么您为什么不选择尽可能短的 ID?
我在代码中使用的字符集有一个优势:它生成的 ID 易于复制粘贴(没有符号,所以双击会选择整个 ID),易于阅读且不会出错(没有相似的字符像2 和Z),而且很容易口头交流(只有大写字母)。只坚持数字是口头交流的最佳选择,但它们并不紧凑。
我确信:给我看代码
Python 3
def int32_to_id(n):
if n==0: return "0"
chars="0123456789ACEFHJKLMNPRTUVWXY"
length=len(chars)
result=""
remain=n
while remain>0:
pos = remain % length
remain = remain // length
result = chars[pos] + result
return result
PowerShell
function int32_to_id($n){
$chars="0123456789ACEFHJKLMNPRTUVWXY"
$length=$chars.length
$result=""; $remain=[int]$n
do {
$pos = $remain % $length
$remain = [int][Math]::Floor($remain / $length)
$result = $chars[$pos] + $result
} while ($remain -gt 0)
$result
}
VBA
Function int32_to_id(n)
Dim chars$, length, result$, remain, pos
If n = 0 Then int32_to_id = "0": Exit Function
chars$ = "0123456789ACEFHJKLMNPRTUVWXY"
length = Len(chars$)
result$ = ""
remain = n
Do While (remain > 0)
pos = remain Mod length
remain = Int(remain / length)
result$ = Mid(chars$, pos + 1, 1) + result$
Loop
int32_to_id = result
End Function
Function id_to_int32(id$)
Dim chars$, length, result, remain, pos, value, power
chars$ = "0123456789ACEFHJKLMNPRTUVWXY"
length = Len(chars$)
result = 0
power = 1
For pos = Len(id$) To 1 Step -1
result = result + (InStr(chars$, Mid(id$, pos, 1)) - 1) * power
power = power * length
Next
id_to_int32 = result
End Function
Public Sub test_id_to_int32()
Dim i
For i = 0 To 28 ^ 3
If id_to_int32(int32_to_id(i)) <> i Then Debug.Print "Error, i=", i, "int32_to_id(i)", int32_to_id(i), "id_to_int32('" & int32_to_id(i) & "')", id_to_int32(int32_to_id(i))
Next
Debug.Print "Done testing"
End Sub