C#:写值成二进制(BIN)文件格式

编程入门 行业动态 更新时间:2024-10-23 16:28:41
本文介绍了C#:写值成二进制(BIN)文件格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此​​,可以说,我有以下值:

So lets say I have the following values:

HEADER01 48 45 41 44 45 52 30 31 06/17/14 30 36 2F 31 37 2F 31 34 1.0 31 2E 30 0x0000 00 0x0027 27 0x0001 01 0x0001 01 0x0001 01 0x0001 01 0x0028 28 192 C0 168 A8 1 01 1 01

  • 第3值是字符串,必须转换为ASCII十六进制值,然后写在.bin文件

    • The first 3 values are STRINGS, should be converted to ASCII HEX values, then written in the .bin file

      接下来的7个值是十六进制,应写成AS-IS在.bin文件

      The next 7 values are HEX, should be written AS-IS in the .bin file

      最后的4个值是整数,应​​该转换为十六进制,然后写在.bin文件

      The last 4 values are INTEGERS, should be converted to HEX, then written in the .bin file

      OUTPUT(BIN)的文件应该是这个样子:

      OUTPUT (.bin) file should look something like this:

      00000000 48 45 41 44 45 52 30 31 30 36 2F 31 37 2F 31 34 00000010 31 2E 30 00 27 01 01 01 01 28 C0 A8 01 01 00 00 00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

    • 是否有可能创建一个(BIN)文件中像这样使用C#.NET?

      Is it possible to create a (.bin) file like this using C# .NET?

      我试过的BinaryWriter,StreamWriter的,但由于某种原因,所有的值写为十六进制的字符串不是我希望他们。

      I tried BinaryWriter, StreamWriter but for some reason all the values are written as HEX strings not as I want them.

      推荐答案

      使用的 的BinaryWriter 是正确的解决方案。

      Using BinaryWriter is the correct solution.

      不要掉入使用 BinaryWriter.Write(字符串) 过载 - 它prefixes用一个字节长度,这是不是你想要的字符串

      Don't fall to the temptation of using the BinaryWriter.Write(String) overload - it prefixes the string with a single-byte length, which is not what you want.

      另外请注意,我的每个值显式地转换为(字节)。如果我没有这样做,编译器会选择写入(INT)过载,写4个字节的文件。

      Also note that I've explicitly cast each value to a (byte). If I hadn't done this, the compiler would have selected the Write(int) overload, writing 4 bytes to the file.

      class Program { static void Main(string[] args) { using (var s = File.OpenWrite("temp.bin")) { var bw = new BinaryWriter(s); bw.Write(Encoding.ASCII.GetBytes("HEADER01")); bw.Write(Encoding.ASCII.GetBytes("06/17/14")); bw.Write(Encoding.ASCII.GetBytes("1.0")); bw.Write((byte)0x00); bw.Write((byte)0x27); bw.Write((byte)0x01); bw.Write((byte)0x01); bw.Write((byte)0x01); bw.Write((byte)0x01); bw.Write((byte)0x28); bw.Write((byte)192); bw.Write((byte)168); bw.Write((byte)1); bw.Write((byte)1); } } }

      结果:

      Result:

更多推荐

C#:写值成二进制(BIN)文件格式

本文发布于:2023-11-08 15:52:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件格式   写值成   BIN

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!