将二进制转换为字符串

Ana*_*hav 1 vbscript

我想将以二进制存储的密码转换为正常的 ASCII 格式,以便我可以读取它。我需要一个 VBscript,脚本也应该返回这个解密的密码

例如:加密的二进制密码:00110001 00110010 00110011 00110100

解密原始密码:1234

我试过这个

'Binary contains the binary password
dim S
For I = 1 To LenB(Binary)
S = S & Chr(AscB(MidB(Binary, I, 1)))
Next
MSGBOX S
Run Code Online (Sandbox Code Playgroud)

但输出是

0
Run Code Online (Sandbox Code Playgroud)

怎样才能做到这一点。请帮忙!!

Tom*_*lak 5

如果您正在处理字节数组,则必须先了解字符编码,然后才能将其转换为字符串。如果没有这些知识,字节将被转换为错误的字符。

ADODB.Stream对象可以处理字节数组。这是一个可以做到这一点的函数:

Const adTypeBinary = 1
Const adTypeText = 2
Const adModeReadWrite = 3

Function BytesToString(bytes, charset)
    With CreateObject("ADODB.Stream")
        .Mode = adModeReadWrite
        .Type = adTypeBinary
        .Open
        .Write bytes
        .Position = 0
        .Type = adTypeText
        .Charset = charset
        BytesToString = .ReadText
    End With
End Function
Run Code Online (Sandbox Code Playgroud)

这是如何使用它:

MsgBox BytesToString(binary, "Windows-1252")
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这是相反的操作:

Function StringToBytes(str, charset)
    With CreateObject("ADODB.Stream")
        .Mode = adModeReadWrite
        .Type = adTypeText
        .Charset = charset
        .Open
        .WriteText str
        .Position = 0
        .Type = adTypeBinary
        StringToBytes = .Read
    End With
End Function
Run Code Online (Sandbox Code Playgroud)

由于您的输入似乎是一个类似于的字符串"00110001 00110010 00110011 00110100",因此这里有一个函数可以将其转换为字节数组,然后您可以将其与BytesToString()上面显示的一起使用:

Function BinaryStringToBytes(binaryStr)
    Dim b, n, i, l

    l = GetLocale
    SetLocale 1031

    With CreateObject("ADODB.Stream")
        .Mode = adModeReadWrite
        .Charset = "Windows-1252"
        .Type = adTypeText
        .Open
        For Each b In Split(binaryStr, " ")
            If Len(b) <> 8 Or Replace(Replace(b, "0", ""), "1", "") <> "" Then
                ' invalid procedure call or argument
                Err.Raise 5, "BinaryStringToBytes", _
                    "Only stings of 8-blocks of 0s and 1s, " & _
                    "separated by a single space are accepted."
            End If
            n = 0
            For i = 0 To 7
                n = n + Mid(b, 8 - i, 1) * 2^i
            Next
            .WriteText Chr(n)
        Next
        .Position = 0
        .Type = adTypeBinary
        BinaryStringToBytes = .Read
    End With

    SetLocale l
End Function
Run Code Online (Sandbox Code Playgroud)

用法

Dim input, output

input = "00110001 00110010 00110011 00110100"
output = BytesToString(BinaryStringToBytes(input), "Windows-1252")

MsgBox output  ' -> "1234"
Run Code Online (Sandbox Code Playgroud)

而且,更重要的是,它可以正确处理多字节编码:

input = "00110001 00110010 00110011 00110100 11000011 10100100"
output = BytesToString(BinaryStringToBytes(input), "UTF-8")

MsgBox output ' -> "1234ä"
Run Code Online (Sandbox Code Playgroud)