我想知道构成字符串的确切字节。
这可能在VBA吗?
类似的东西:
> Debug.Print toHex("@E")
0x40, 0x45
这个问题的原因:
我在使用ServerXMLHTTP时遇到编码问题。
(不确定数据在哪个位置被错误地解释)
对于debuging目的,我想看看字符串中的实际字节是什么,所以我可以缩小问题的来源。
答案 0 :(得分:2)
我发现您在评论中找到了实际问题的答案,但只是为了回答您的具体问题:
您可以使用下面的toHex
方法将字符串转换为原始字节。我在Main
中添加了一个使用示例,评论应该解释发生了什么:
Public Sub Main()
Dim str As String
str = "This is a String"
Debug.Print toHex(str)
End Sub
Public Function toHex(str As String) As String
'dim an dynamic Byte array
Dim arrBytes() As Byte
'When you assign the string to the undimensioned Byte array,
'VBA automatically resizes it and makes a copy of the individual
'bytes of the String. Each character is two bytes
'(I believe VBA uses UTF-16).
arrBytes = str
'This prints out the bytes in the way you describe in your question.
Dim strOut As String
If UBound(arrBytes) > 0 Then
strOut = "0x" & arrBytes(0)
For i = 1 To UBound(arrBytes)
strOut = strOut & ", 0x" & Hex(arrBytes(i))
Next
End If
toHex = strOut
End Function
修改强>
将字符串分配给字节数组将完全复制字节。本地,VBA使用UTF-16。但是,如果您从其他来源提取数据,则可能是ASCII或UTF-8。 VBA仍将尝试将字符串显示为UTF-16 - 也就是说,它将尝试将每2个字节(16位)显示为单个字符。您可以通过在Byte数组中手动构建ASCII字符串并将其分配给String,然后尝试显示它来查看此行为:
Public Sub Main()
Dim strMessage As String
strMessage = "Hello World!"
Debug.Print strMessage 'displays "Hello World!" in the immediate window
Debug.Print toHex(strMessage) 'displays:
'0x72, 0x0, 0x65, 0x0, 0x6C, 0x0, 0x6C, 0x0, 0x6F, 0x0, 0x20, 0x0, 0x57, 0x0, 0x6F, 0x0, 0x72, 0x0, 0x6C, 0x0, 0x64, 0x0, 0x21, 0x0
'Note the null bytes because each 2 bytes is a UTF-16 pair
strMessage = StrConv("Hello World!", vbFromUnicode) 'Converts the immediate string to ASCII and stores it in the VBA String variable
Debug.Print strMessage 'displays "??????" in the immediate window - 6 unprintable characters because it interprets each two ASCII bytes as a single unprintable UTF-16 character
Debug.Print toHex(strMessage) 'displays:
'0x72, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21
'Note that these are the ASCII bytes of the individual letters
End Sub