VBS字符串编码转换函数代码(vb字符串转换为文本类型)墙裂推荐

随心笔谈2年前发布 admin
194 0 0

文章摘要

这篇文章介绍了三个函数,用于在不同字符编码之间进行转换。这些函数通过ADODB.Stream对象实现了字符编码转换的功能: 1. `StringToBytes`函数将输入字符串(指定字符集)转换为字节数组。 2. `BytesToString`函数将字节数组转换为指定字符集的字符串。 3. `AlterCharset`函数通过中间转换(字节中间人)将一个字符集的字符串转换为另一个字符集的字符串。 这些函数的核心目的是解决字符编码转换问题,特别是在Windows环境下处理1字节字符集之间的转换。

Const adTypeBinary=1
Const adTypeText=2

‘ accept a string and convert it to Bytes array in the selected Charset
Function StringToBytes(Str,Charset)
Dim Stream : Set Stream=CreateObject(“ADODB.Stream”)
Stream.Type=adTypeText
Stream.Charset=Charset
Stream.Open
Stream.WriteText Str
Stream.Flush
Stream.Position=0
‘ rewind stream and read Bytes
Stream.Type=adTypeBinary
StringToBytes=Stream.Read
Stream.Close
Set Stream=Nothing
End Function

‘ accept Bytes array and convert it to a string using the selected charset
Function BytesToString(Bytes, Charset)
Dim Stream : Set Stream=CreateObject(“ADODB.Stream”)
Stream.Charset=Charset
Stream.Type=adTypeBinary
Stream.Open
Stream.Write Bytes
Stream.Flush
Stream.Position=0
‘ rewind stream and read text
Stream.Type=adTypeText
BytesToString=Stream.ReadText
Stream.Close
Set Stream=Nothing
End Function

‘ This will alter charset of a string from 1-byte charset(as windows-1252)
‘ to another 1-byte charset(as windows-1251)
Function AlterCharset(Str, FromCharset, ToCharset)
Dim Bytes
Bytes=StringToBytes(Str, FromCharset)
AlterCharset=BytesToString(Bytes, ToCharset)
End Function

© 版权声明

相关文章