If you are dealing with a byte array, you must know the character encoding before you can convert it to string. Without that knowledge the bytes will be converted to the wrong characters.
The ADODB.Stream
object can handle byte arrays. Here is a function that that does that:
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
And here is how to use it:
MsgBox BytesToString(binary, "Windows-1252")
For the sake of completeness, this is the reverse operation:
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
Since your input seems to be a string like "00110001 00110010 00110011 00110100"
, here is a function to convert that to a byte array, which you can then use with BytesToString()
shown above:
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
Usage
Dim input, output
input = "00110001 00110010 00110011 00110100"
output = BytesToString(BinaryStringToBytes(input), "Windows-1252")
MsgBox output ' -> "1234"
And, more importantly, it can handle multi-byte encodings properly:
input = "00110001 00110010 00110011 00110100 11000011 10100100"
output = BytesToString(BinaryStringToBytes(input), "UTF-8")
MsgBox output ' -> "1234ä"