C#字节格式的区别

Sha*_*777 -1 c#

我试图通过我的 xampp 服务器下载一些字节以在我的 C# 程序中使用它,但字节长度之间存在差异,如下所示:

        WebClient wc = new WebClient();
        byte[] bytesweb = wc.DownloadData(@"http://127.0.0.1/test.txt");

        int lenweb = bytesweb.Length; //The value of lenweb is 69
        
Run Code Online (Sandbox Code Playgroud)

然后当我直接在程序中使用相同的字节时,如下所示:

        byte[] bytesapp = new byte[] { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

        int lenapp = bytesapp.Length; //The value of lenapp is 11
Run Code Online (Sandbox Code Playgroud)

所以我不明白这 2 之间发生了什么变化,在使用我的服务器导入它时该怎么做,以使长度值等于“11”

注意:“test.txt”的值为:{ 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

Hei*_*nzi 5

注意:“test.txt”的值为:{ 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

因此,您的文件包含文字文本{ 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

这是一个69 字节的文本当解释为 C# 代码片段时,表示一个11 字节的字节数组。这解释了您所看到的差异。


你如何解决这个问题?不要将字节数组存储为文本,而是将它们存储为字节:

byte[] bytesapp = new byte[] { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

// This creates the file you want to put on your web server.
File.WriteAllBytes(@"C:\temp\test.bin", bytesapp);
Run Code Online (Sandbox Code Playgroud)

(或者,您可以编写代码来解析文本文件并将其转换为“真正的”字节数组。如果您以以下格式存储数据,则此问题包含可以为您执行此操作的示例代码:0000400000e81000000040。)