c# - ASCII.GetString() 在空字符处停止

标签 c# ascii

我有一个大问题... 我的一段代码:

string doc = System.Text.Encoding.ASCII.GetString(stream);

变量 doc 以第一个空字符 (/0) 结束(此时丢失了大量数据)。我想得到整个字符串。 更重要的是,当我复制这段代码并在 Visual Studio 的即时窗口中运行时 - 一切都很好......

我做错了什么?

最佳答案

不,它没有:

string doc = System.Text.Encoding.ASCII.GetString(new byte[] { 65, 0, 65 }); // A\0A
int len = doc.Length; //3

但是 Winforms(和 Windows API)首先截断(显示时)\0

示例:https://dotnetfiddle.net/yjwO4Y

我要补充一点(在 Visual Studio 2013 中),\0 正确显示但在一个地方:如果您激活 Text Visualizer(放大镜),那不会支持 \0 并截断它。

为什么会这样?因为历史上有两个字符串“模型”,NUL (\0) 终止的 C 字符串(因此不能使用 \0 作为字符)和具有长度前缀的 Pascal 字符串,因此可以将 \0 作为字符。来自wiki

Null-terminated strings were produced by the .ASCIZ directive of the PDP-11 assembly languages and the ASCIZ directive of the MACRO-10 macro assembly language for the PDP-10. These predate the development of the C programming language, but other forms of strings were often used.

现在,Windows 是用 C 语言编写的,并使用以 null 结尾的字符串(但后来 Microsoft 改变了想法,COM 字符串更类似于 Pascal 字符串并且可以包含 NUL 字符)。所以 Windows API 不能使用 \0 字符(除非它们是基于 COM 的,而且基于 COM 的可能经常有问题,因为它们没有针对 \0 进行全面测试)。对于 .NET,Microsoft 决定使用类似于 Pascal 字符串和 COM 字符串的东西,因此 .NET 字符串可以使用 \0

Winforms 直接建立在 Windows API 之上,因此它无法显示 \0。 WPF 是在 .NET 中“从头开始”构建的,因此通常它可以显示 \0 字符。

关于c# - ASCII.GetString() 在空字符处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29362493/

相关文章:

c# - ajax beginForm 传递路由值和按钮值

c# - LINQ 中的多个左连接

c# - Azure 移动服务客户端将参数传递给 .NET 后端

php - 如何使用 PHP/HTML 保留空格格式?

encoding - Dart的ASCII-8位编码

java - 在 Java 中构造时设置数组值

C# snippet 创建片段

c# - ClickOnce 应用程序替换当前安装的文件

Python:使用 ascii 码打印

rust - 将 ASCII 数字标准化为数字