Deep BlueVBScriptWMIPHPC语言JavaScriptWindows API路由器Windows函数Python

VBS任意进制转换(实现PHP的base_convert函数)

昨天在临风小筑上看到一篇《ASP/VBS任意进制转换》,代码写得怎么样暂且不评论,但函数名称起得实在是不敢恭维,看名称根本不知道这两个函数是做什么的。

我参考 PHP 的 base_convert 函数的 C 语言源码,实现 VBS 版的任意进制转换函数 base_convert。有了这个函数,就可以很轻松的进行二、八、十、十六进制转换。

Function base_convert(number, frombase, tobase)
    'Author: Demon
    'Date: 2011/12/17
    'Website: http://demon.tw

    Dim digits, num, ptr, i, n, c
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    
    If frombase < 2 Or frombase > 36 Then
        Err.Raise vbObjectError + 7575,,"Invalid from base"
    End If
    
    If tobase < 2 Or tobase > 36 Then
        Err.Raise vbObjectError + 7575,,"Invalid to base"
    End If
    
    number = CStr(number) : n = Len(number)
    
    For i = 1 To n
        c = Mid(number, i, 1)
        
        If c >= "0" And c <= "9" Then
            c = c - "0"
        ElseIf c >= "A" And c <= "Z" Then
            c = Asc(c) - Asc("A") + 10
        ElseIf c >= "a" And c <= "z" Then
            c = Asc(c) - Asc("a") + 10
        Else
            c = frombase
        End If
        
        If c < frombase Then
            num = num * frombase + c
        End If
    Next
        
    Do
        ptr = ptr & Mid(digits, (num Mod tobase + 1), 1)
        num = num \ tobase
    Loop While num
    
    base_convert = StrReverse(ptr)
End Function

WScript.Echo base_convert("A37334", 16, 2)
WScript.Echo base_convert("http://demon.tw", 16, 10)

http://ken.gw.to/