VBMAN.ToolsUtf8 - UTF-8 Encoding/Decoding Object
Overview
VBMAN.ToolsUtf8 provides conversion functionality between UTF-8 encoding and VB strings/byte arrays, serving as the foundation tool for processing Chinese and international text.
Core Features
- Encoding Conversion: Convert between strings and UTF-8 byte arrays
- Socket Friendly: Directly process network transmission data
- Automatic BOM Handling: Automatically identify and skip UTF-8 BOM
Methods
Decode
Decode UTF-8 byte array to string
vb
Public Function Decode(bytes() As Byte) As StringParameters:
bytes- UTF-8 encoded byte array
Returns: Decoded VB string
Example:
vb
' Receive data from Socket and decode
Dim bytes() As Byte
Client.GetData bytes, vbArray
Dim text As String
text = VBMAN.ToolsUtf8.Decode(bytes)
Debug.Print textEncode
Encode string to UTF-8 byte array
vb
Public Function Encode(text As String) As Byte()Parameters:
text- String to encode
Returns: UTF-8 encoded byte array
Example:
vb
' Encode string and send
Dim text As String
text = "Hello World"
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode(text)
Client.SendData bytesComprehensive Examples
Example 1: Socket Communication Encoding/Decoding (from cs-auther case)
vb
' Get data from Socket and UTF-8 decode
Dim json As New cJson
Dim bytes() As Byte
Client.GetData bytes, vbArray
json.Decode VBMAN.ToolsUtf8.Decode(bytes)
' Process message...Example 2: File Encoding Conversion
vb
Private Sub ConvertToUtf8(sourcePath As String, destPath As String)
' Read source file (assumed to be ANSI)
Dim fso As New Scripting.FileSystemObject
Dim ts As TextStream
Set ts = fso.OpenTextFile(sourcePath, ForReading, False, TristateFalse)
Dim content As String
content = ts.ReadAll
ts.Close
' Convert to UTF-8 and save
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode(content)
' Save byte array
Dim fileNum As Integer
fileNum = FreeFile
Open destPath For Binary As #fileNum
Put #fileNum, , bytes
Close #fileNum
End SubExample 3: HTTP Request Content Processing
vb
Private Sub SendHttpPost(url As String, jsonData As String)
' Encode JSON data
Dim postData() As Byte
postData = VBMAN.ToolsUtf8.Encode(jsonData)
' Send HTTP request
With VBMAN.HttpClient
.Url = url
.Method = "POST"
.ContentType = "application/json; charset=utf-8"
.Body = postData
.Send
End With
End SubExample 4: Console Output Chinese
vb
Private Sub PrintToConsole(message As String)
' Convert Unicode string to UTF-8 byte array
Dim bytes() As Byte
bytes = VBMAN.ToolsUtf8.Encode(message)
' Output to console (requires API support)
' WriteConsole ...
End SubBest Practices
- Network Communication: Use UTF-8 encoding uniformly when Socket transmits Chinese
- File Exchange: Use UTF-8 encoding when exchanging files with other systems
- Web Interaction: HTTP request/response Body usually uses UTF-8
- Database Storage: If needing to store Chinese in byte form, use UTF-8