Base conversion function in VBScript

后端 未结 3 693
清歌不尽
清歌不尽 2021-01-25 01:07

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

3条回答
  •  醉酒成梦
    2021-01-25 01:25

    To encode negative numbers in binary like calc in Programmer mode, i.e. an integer only mode (but VBScript reduces precise up to 32 bits only):

    option explicit
    On Error GoTo 0
    Dim xx
    xx = 45
    Wscript.Echo +xx, vbTab, Base2( xx, False), Base2( xx, True)
    Wscript.Echo -xx, vbTab, Base2(-xx, False), Base2(-xx, True)
    
    Function Base2( iNum, bLong)
      Dim ii, octets, sNum, iLen
      octets = Array ( "000","001", "010", "011", "100", "101", "110", "111")
      If bLong Or Len( CStr( Hex( -Abs(iNum)))) > 4 Then
        sNum = CStr( Oct(CLng(iNum)))   'force Long  : DWORD (32 bits/4 bytes)
        iLen = 32
      Else
        sNum = CStr( Oct(CInt(iNum)))   'keep Integer:  WORD (16 bits/2 bytes)
        iLen = 16
      End If
      Base2 = ""
      For ii = 1 To Len( sNum)
        Base2 = Base2 & octets( Mid( sNum, ii, 1))
      Next
      Do While Len( Base2) > 1 And Left( Base2, 1) = "0"
        Base2 = Mid( Base2, 2)          'truncate left zeroes
      Loop
      'expand left zeroes for a positive value?  
      'Base2 = Right( String( iLen, "0") & Base2, iLen)
    End Function
    

    Output:

    ==>cscript //NOLOGO D:\VB_scripts\SO\32416311.vbs
    45       101101 101101
    -45      1111111111010011 11111111111111111111111111010011
    
    ==>
    

    Output with Base2 = Right( String( iLen, "0") & Base2, iLen) uncommented up:

    ==>cscript //NOLOGO D:\VB_scripts\SO\32416311.vbs
    45       0000000000101101 00000000000000000000000000101101
    -45      1111111111010011 11111111111111111111111111010011
    
    ==>
    

提交回复
热议问题