Search code examples
vbscriptradix

Base conversion function in VBScript


Is there a function built into VBScript (for wscript or cscript) that would take a number and convert it to base 2?

For example, Base2(45) would output "101101".


Solution

  • I'm not aware of anything built-in, but it's easy enough to create a general-purpose routine that can handle binary and other bases. If you define symbols from 0 to Z, you can handle everything up to base 36, for example.

    Function ToBase(ByVal n, b)
    
        ' Handle everything from binary to base 36...
        If b < 2 Or b > 36 Then Exit Function
    
        Const SYMBOLS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
        Do
            ToBase = Mid(SYMBOLS, n Mod b + 1, 1) & ToBase
            n = Int(n / b)
        Loop While n > 0
    
    End Function
    

    For your example, just pass 2 for the base:

    WScript.Echo ToBase(45, 2)
    

    Output:

    101101