【发布时间】:2013-04-22 05:51:20
【问题描述】:
我正在尝试将 UTF-8 编码的字符串转换为 VB.NET 中的 windows-1255,但没有成功。诚然,我不了解 VB,但尝试使用 MSDN 上的示例并根据我的需要对其进行修改:
Public Function Utf82Hebrew(ByVal Str As String) As String
Dim ascii As Encoding = Encoding.GetEncoding("windows-1255")
Dim unicode As Encoding = Encoding.Unicode
' Convert the string into a byte array.
Dim unicodeBytes As Byte() = unicode.GetBytes(Str)
' Perform the conversion from one encoding to the other.
Dim asciiBytes As Byte() = Encoding.Convert(unicode, ascii, unicodeBytes)
' Convert the new byte array into a char array and then into a string.
Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)-1) As Char
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
Dim asciiString As New String(asciiChars)
Utf82Hebrew = asciiString
End Function
这个函数实际上并没有做任何事情——字符串仍然是 UTF-8。但是,如果我更改此行:
Dim ascii As Encoding = Encoding.GetEncoding("windows-1255")
到这里:
Dim ascii As Encoding = Encoding.ASCII
然后函数返回问号代替字符串。
有谁知道如何将 UTF-8 字符串正确转换为特定编码(在本例中为 windows-1255),和/或我在上面的代码中做错了什么?
提前致谢。
【问题讨论】:
-
您要转换什么文本?
-
它可以是在 Web 表单中输入的任何希伯来语字符串。示例:שלום
-
没有“utf-8 字符串”之类的东西,字符串在 .NET 中始终以 utf-16 编码。 utf-8 只能存储在 byte[] 中。在您以某种方式将 utf-8 字节转换为字符串后,原始数据被破坏而无法修复,utf-8 包含没有 utf-16 表示的字节值。您需要从根本上解决此问题并修复生成“Str”参数的代码。
-
A
System.String在 .net 中始终是 UTF-16。 Utf-8 字符串将在 .net 中表示为字节数组。