为什么这个ASCII字符输出为空字符串(VB.NET)?

时间:2013-03-05 17:10:44

标签: vb.net character-encoding ascii

我正在尝试将ASCII字符131(ƒ - 带钩的拉丁小写字母f)输出到消息框中,但由于某些奇怪的原因,它显示为空字符串。我有以下VB.NET代码:

Dim str As String = Convert.ToChar(131)
MessageBox.Show(str, "test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Debug.Print(str)

在上面,消息框没有显示任何内容,只是debug.print语句在“立即窗口”中正确显示了该字符。我有大约70个其他ascii字符,这些方法都可以正常使用此方法,但只有少数几个显示为空白(131和EN短划线150)。

例如,以下作品:

str = Convert.ToChar(164)
MessageBox.Show(str, "test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Debug.Print(str)

我也尝试过转换为UTF8,但我得到的行为与第一段代码相同:

Dim utf8Encoding As New System.Text.UTF8Encoding(True)
Dim encodedString() As Byte
str = Convert.ToChar(131)
encodedString = utf8Encoding.GetBytes(str)
Dim str2 As String = utf8Encoding.GetString(encodedString)
MessageBox.Show(str2, "test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Debug.Print(str2)

这是编码问题吗?感谢您的任何见解。

编辑:只是为了澄清,我实际上并没有尝试将字符输出到消息框。那段代码只是一个考验。我试图将字符作为字符串传递给在第三方xml编辑器控件中使用它的函数,但它显示为空白。即使在Visual Studio中进行调试,您也可以看到它的值等于“”。

编辑2:感谢下面接受的答案中的一些调查,我发现我使用了错误的unicode字符。对于这个f字符,使用的代码是ToChar(402)。这非常有效。谢谢大家。

1 个答案:

答案 0 :(得分:4)

正如其他人所说,“ƒ”字符不是ASCII字符。 ASCII严格来说是7字节格式,“扩展ASCII”字符完全不同,具体取决于您引用的编码。例如,Windows CodePage 1250的字符131(0x83)为空,但CodePage 1252在该插槽中有“ƒ”字符。

我在下面的示例中使用了1252,但是如果要转换更大的编码ASCII文本,则应确保正确识别正在使用的编码并使用正确的代码页进行转换。

我认为,处理此问题的最佳方法是将所有内容转换为Unicode并远离扩展ASCII,除非出于遗留原因绝对必要。但是,要获得“ƒ”字符,您可以这样做,例如:

Imports System.Text

然后:

Dim enc1252 As Encoding = Encoding.GetEncoding(1252)
Dim bArr(0) As Byte
bArr(0) = CByte(131)

Dim str2 As String = Encoding.Unicode.GetString( _
                     Encoding.Convert(enc1252, Encoding.Unicode, bArr))

MessageBox.Show(str2, " test", MessageBoxButtons.OK, _
                MessageBoxIcon.Information)

然而,VisualStudio本身使用Unicode,因此如果您只需要显示“ƒ”字符,而不需要实际转换任何旧文本,您可以随时执行:

MessageBox.Show("ƒ", " test", MessageBoxButtons.OK, _
                MessageBoxIcon.Information)
相关问题