Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1531

Safer way to convert full ANSI strings

$
0
0
Thanks to wqweto, I found a faster and safer way to convert full ANSI strings to byte array.
Code:

Option Explicit

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)

Private Sub DebugPrintByte(sDescr As String, bArray() As Byte)
    Dim lPtr As Long
    Debug.Print sDescr & ":"
    If GetbSize(bArray) = 0 Then Exit Sub
    For lPtr = 0 To UBound(bArray)
        Debug.Print Right$("0" & Hex$(bArray(lPtr)), 2) & " ";
        If (lPtr + 1) Mod 16 = 0 Then Debug.Print
    Next lPtr
    Debug.Print
End Sub

Private Function GetbSize(bArray() As Byte) As Long
    On Error GoTo GetSizeErr
    GetbSize = UBound(bArray) + 1
    Exit Function
GetSizeErr:
    GetbSize = 0
End Function

Private Sub Command1_Click()
    Dim sTmp As String
    Dim bTmp() As Byte
    sTmp = "0123456789ƒ„…†‡ˆ"
    ReDim bTmp(Len(sTmp) - 1)
    CopyMemory bTmp(0), ByVal sTmp, Len(sTmp)
    DebugPrintByte "bTmp", bTmp
    ReDim bTmp(LenB(sTmp) - 1)
    CopyMemory bTmp(0), ByVal StrPtr(sTmp), LenB(sTmp)
    DebugPrintByte "bTmp", bTmp
End Sub

The end 6 characters of the string are ANSI characters &H83 to &H88.
bTmp:
30 31 32 33 34 35 36 37 38 39 83 84 85 86 87 88

However, when VB stores the characters as wide characters, it converts them to Unicode characters.
bTmp:
30 00 31 00 32 00 33 00 34 00 35 00 36 00 37 00
38 00 39 00 92 01 1E 20 26 20 20 20 21 20 C6 02

J.A. Coutts

Viewing all articles
Browse latest Browse all 1531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>