2017-12-28 11 views
0

나는 다음과 같은 문제가있다.를 Base64 인코딩 바이트 VBA

다음은 내가 시도한 코드입니다. 그것은 작동하지만 예상 한 출력을 얻지 못했습니다. AAB/AQatAQIBAA의 ==

하지만 예상 : : 함수에서 출력은 내가 그렇게 할 수있는 방법 AAECAa0GAX8AAA의 ==

을 VBA 또는 심지어 가능하다?

Private Function encodeBase64(ByRef arrData() As Byte) As String 
Dim objXML As MSXML2.DOMDocument 
Dim objNode As MSXML2.IXMLDOMElement 

Set objXML = New MSXML2.DOMDocument 

Set objNode = objXML.createElement("b64") 
objNode.DataType = "bin.base64" 
objNode.nodeTypedValue = arrData 
encodeBase64 = objNode.text 

Set objNode = Nothing 
Set objXML = Nothing 
End Function 

Function bin2Byte(ByVal s As String) As Byte() 
Dim bitsIn As Long 
bitsIn = 8 

Dim i As Long 
'pad with zeros 
If Len(s) Mod bitsIn <> 0 Then 
    For i = 1 To bitsIn - Len(s) Mod bitsIn 
     s = "0" & s 
    Next i 
End If 

i = Len(s) 
Dim bytes() As Byte 
Dim byteCount As Long 
byteCount = -1 
Dim sByte As String 
Do While LenB(s) > 0 
    byteCount = byteCount + 1 
    ReDim Preserve bytes(byteCount) 

    sByte = Mid$(s, Len(s) - bitsIn + 1) 
    'sByte = Mid$(s, 1, bitsIn) 
    For i = 0 To 7 Step 1 
     bytes(byteCount) = bytes(byteCount) + CLng(Mid$(sByte, 8 - i, 1)) * 2^i 
    Next i 
    s = Mid$(s, 1, Len(s) - bitsIn) 
    's = Mid$(s, bitsIn + 1) 
Loop 
bin2Byte = bytes 
End Function 

Sub tester() 
'note we can't add any 0 padding to the test binary string 
Dim bin As String 
bin = "00000000000000010000001000000001101011010000011000000001011111110000000000000000" 
Dim binOut As String 
binOut = encodeBase64(bin2Byte(bin)) 

Debug.Print (binOut) 
End Sub 

Screenshot

+6

말 그대로 봤 "Base64로 인코딩 VBA에서 바이트"과는 엄청나게 많은 안타! – Absinthe

+0

나도 노력했지만 그 중 아무 것도 작동하지 않았거나 도와 주었다. –

+0

@MaThias 코드를 게시 할 수 있습니까? 이미 시도 했습니까? – AntiDrondert

답변

0

귀하의 문제는 Base64로 인코딩하지만 bin2Byte하지입니다. 입력 문자열에 표시된 비트를 올바르게 구문 분석하지 않습니다.

이 기능을 사용하는 대신 문자열에서 바이트를 얻을 수 있습니다 :

Public Function BinStr2Bytes(ByVal str As String) As Byte() 
    If Len(str) Mod 8 Then Err.Raise 5, , "Invalid length (needs to be a multiple of 8)" 

    Dim bytes() As Byte, i As Long, j As Long 
    ReDim bytes(0 To Len(str) \ 8 - 1) 

    For i = 1 To Len(str) 
     j = (i - 1) \ 8 
     bytes(j) = bytes(j) * 2 - (AscW(Mid(str, i, 1)) = 49) 
    Next 

    BinStr2Bytes = bytes 
End Function