简体   繁体   中英

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 ).

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 ).

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 ?

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:

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.

Also, when I type a single byte, let's say FE, it writes FE000000. If I type FAFBFCFDFE, it gives me an error - "Value was either too large or too small for UInt32".

Do you know why is it doing this?

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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