swift中提供了一个方法可以快速将十进制转为其他进制
但是这个方法仅限于2-36进制之间
比如:
let number = 6664538181143920600 //十进制转二进制 let conver2Str = String.init(number, radix: 2, uppercase: false) print("101110001111101001100100010101001011111000111000111111111011000") //十进制十六进制 let conver8Str = String.init(number, radix: 16, uppercase: false) print("5c7d322a5f1c7fd8")
但是美团外卖有个出餐码,需要将十进制转为62进制,这个方法就不能满足,所以就自己写了一个方法来转:
func converIntRadix62(number: Int, radix: Int) -> String { var intNo = number let digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var result = "" while intNo > 0 { let idx = digits.index(digits.startIndex, offsetBy: Int(intNo % radix)) let digit = digits[idx] var digitStr = "" digitStr.append(digit) result = digitStr + result intNo = intNo / radix } return result } //十进制转62进制 let conver16Str = converIntRadix62(number: number, radix: 62) print("4VeFjRhKx8")