因此,可以说,我有以下值:
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)文件格式
发布评论