简体   繁体   English

在C#(BinaryWriter)中写入多个十六进制值

[英]Write multiple hex values in C# (BinaryWriter)

I want to allow the user to write multiple bytes in a textbox ( textBox1 ) to a hexadecimal offset ( toolStripTextBox1 ). 我想允许用户将文本框( textBox1 )中的多个字节写入十六进制偏移量( toolStripTextBox1 )。

The code is: 代码是:

using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(ofd.FileName)))
{
     bw.Seek(toolStripTextBox1.Text, SeekOrigin.Begin);
     bw.Write((byte)textBox1.Text);
}    

Unfortunately, it only writer one byte, so let's say I put in textBox1 3F468A and in toolStripTextBox1 F00000 , it will write at offset 0xF00000 just the last byte in the 3 bytes I put in textBox1 ( 8A ). 不幸的是,它仅写入一个字节,所以,假设我将其放在textBox1 3F468AtoolStripTextBox1 F00000 ,它将在偏移量0xF00000处写入恰好是我在textBox18A )中输入的3个字节。

How do I make it write multiple bytes from the textBox1 , so at 0xF00000 , the BinaryWriter will write the hex value 3F468A , and not just 8A ? 我如何使其从textBox1写入多个字节,所以在0xF00000BinaryWriter将写入十六进制值3F468A ,而不仅仅是8A

To be clear, neither of your text boxes contain numeric data. 明确地说,您的两个文本框都不包含数字数据。 You need to convert the strings in your text boxes to the correct numeric data type. 您需要将文本框中的字符串转换为正确的数字数据类型。

Once you've done your conversions correctly, just use the right Write overload: 正确完成转换后,只需使用正确的Write重载即可:

var seekPos = int.Parse(toolStripTextBox1.Text, NumberStyles.HexNumber);
var data = UInt32.Parse(textBox1.Text, NumberStyles.HexNumber);
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(ofd.FileName)))
{
     bw.Seek(seekPos, SeekOrigin.Begin);
     bw.Write(data); //data is UInt32, correct overload is chosen
}   

spender, 消费者

Thanks for answering, I really appreciate that: 感谢您的回答,我非常感谢:

 var seekPos = int.Parse(toolStripTextBox1.Text,
 NumberStyles.HexNumber); var data = UInt32.Parse(textBox1.Text,
 NumberStyles.HexNumber); using (BinaryWriter bw = new
 BinaryWriter(File.OpenWrite(ofd.FileName))) {
      bw.Seek(seekPos, SeekOrigin.Begin);
      bw.Write(data); //data is UInt32, correct overload is chosen }

I have tried the code, it works really good, but it writes it in reverse hex (as half word), so if I put in textBox1 424344, it writes in the hex data 44434200. 我已经尝试过该代码,它的工作原理非常好,但是它以反十六进制形式(作为半字)写入,因此,如果我将其放入textBox1 424344中,它将写入十六进制数据44434200。

Also, when I type a single byte, let's say FE, it writes FE000000. 另外,当我键入一个字节时,假设FE,它写的是FE000000。 If I type FAFBFCFDFE, it gives me an error - "Value was either too large or too small for UInt32". 如果我键入FAFBFCFDFE,它会给我一个错误-“对于UInt32,值太大或太小”。

Do you know why is it doing this? 你知道为什么要这么做吗?

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM