Skip to content

Commit 6c6f036

Browse files
committed
Base62: 10 to 62 encode string
1 parent 0132f4b commit 6c6f036

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

base62.rb

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Base62
2+
3+
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split('')
4+
5+
class << self
6+
# 输入十进制整数,得到62进制的字符串
7+
def encode_string(i)
8+
digits = encode(i)
9+
get_string62(digits)
10+
end
11+
12+
def encode(i)
13+
digits = []
14+
base = ALPHABET.size
15+
16+
while i > 0 # i < 0 时,说明已经除尽了,已经到最高位,数字位已经没有了
17+
remainder = i % base # 取余 得到最后一位
18+
digits << remainder
19+
i = i / base # 由于上面已经取余得到一位了,现在取整 减掉一位
20+
end
21+
digits
22+
end
23+
24+
# 输出字符串,长度为6
25+
def get_string62(digist)
26+
str = ''
27+
6.times.each do |i|
28+
d_value = digist[i]
29+
if d_value.present?
30+
d_value = d_value -1 #位数从0开始
31+
str = ALPHABET[d_value] + str
32+
else
33+
str = 'a' + str
34+
end
35+
end
36+
37+
str
38+
end
39+
40+
# 将str转为十进制数
41+
def base62_to_dec(str)
42+
result = 0
43+
str.split(//).each_with_index do |v, i|
44+
result = result + (ALPHABET.index(v) + 1) * 62**(5-i) if v != 'a'
45+
end
46+
result
47+
end
48+
49+
end
50+
end
51+
52+
# 进制的转换:
53+
54+
# 1 取余操作%,得到最后一位,
55+
# 2 之后整除/操作,过滤调上一步已经得到的一位
56+
# 3 重复 1 直到 结果< 0 说明位数已经操作完了

0 commit comments

Comments
 (0)