将字符串转换为十六进制/字节数组 VB



我目前正在从事需要简单字符串的项目:

string ("Example") 

并转换为十六进制字节数组:

HexByteArray(45 ,78 ,61 ,6d ,70 ,6c ,65)

在 VBA 中,我使用 strconv 实现了这一目标:

bytes = StrConv(id, vbFromUnicode)

努力在 VB 中找到等效功能,到目前为止,我已经设法使用 Hex() 函数创建了一个整数等效功能,但如前所述,我需要将每个字符十六进制等效存储在字节数组中。可能是一个简单的解决方案,感谢所有的帮助!

Sub GetHexString(Value As String)
    Dim Bytes() As Byte = Text.Encoding.ASCII.GetBytes(Value)
    ' StringBuilder Capacity for 2 characters plus space per byte
    With New StringBuilder(Bytes.Length * 3)
        For Each B As Byte In Bytes
            ' note the trailing space in the format
            .AppendFormat("{0:x2} ", B)
        Next
        Debug.Print(.ToString.Trim)
        ' If you want an array of strings, split on the spaces
        Dim HexString() As String = Split(.ToString.Trim, " ")
    End With
End Sub

GetHexString("example")的输出:

45 78 61 6d 70 6c 65

最新更新