10-62位进制转换



class OfflineDataUtil: NSObject {
    /// 生成OfflineId
    public class func getOfflineId(date: Date? = sysServerTime()) -> String {
        let timeInterval: TimeInterval = date?.timeIntervalSince1970 ?? 0
        let millisecond = CLongLong(round(timeInterval*1000))
        let timestamp = Int(millisecond)
        return string10to62(number:timestamp ) + "-" + getRandom62(len: 8)
    }
    
    private class func getRandom62(len: Int) -> String {
        var s: [String] = []
        let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        let hexDigits = str.split()
        
        for _ in 0..<len {
            let index = Int(arc4random()%UInt32(str.count - 1))
            s.append(hexDigits[index])
        }
        return s.joined()
    }
    
    private class func string10to62(number: Int) -> String {
        let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        let chars = str.split()
        let radix = chars.count
        var qutient = +number
        var arr: [String] = []
        
        repeat{
            let mod = qutient % radix
            qutient = (qutient - mod) / radix
            arr.insert(chars[mod], at: 0)
        }while qutient > 0
        return arr.joined()
    }
    
    public class func string62to10(number_code: String) -> Double {
        let str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        let chars = str.split()
        let radix = str.count
        let number_code = String(number_code)
        let len = number_code.count
        
        var origin_number: Double = 0
        
        for i in 0..<len {
            
            let codeIndex = len - i - 1
            
            let code = number_code.split()[codeIndex]
            for j in 0..<chars.count {
                
                let char = chars[j]
                if char == code {
                    origin_number += pow(Double(radix), Double(i)) * Double(j)
                    break
                }
            }
        }
        
        return origin_number
    }
}

extension String {
    func split() -> [String] {
        return self.map(String.init)
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值