Search code examples
c#hexarraysdecimalbinarywriter

Decimal to ByteArray & write to offset


I want to know how I would convert from a decimal number located in a text box to hexadecimal and then to a byte array and write this array to the offset I want, using BinaryWriter.

My textBox11 decimal value is "101200001" and I need to write the it's Hexadecimal value, which is "06 08 30 81", into a file at a speciffic offset.

This is the what I have, but I'm missing the conversion from textBox11.Text to byteArray.

    int index = listBox1.SelectedIndex;
    int startOffset = 0x00000008;
    int itemIDDiff = 0x00000328;

    BinaryWriter bw = new BinaryWriter(File.Open(_FileName, FileMode.Open));
    bw.BaseStream.Seek(startOffset + itemIDDiff * index, SeekOrigin.Begin);
    bw.Write( /* textBox11.Text converted to HEX then to byte array? */ );
    bw.Close();

This is part of the file that I need to write to:

00000330h: 02 00 00 00 00 00 00 00 4A 61 64 65 20 45 61 72 ; ........Jade Ear
00000340h: 72 69 6E 67 00 00 00 00 00 00 00 00 00 00 00 00 ; ring............

let's say I want to change the "02 00 00 00" to "06 08 30 81". How would I do this using the BinaryWriter?


Solution

  • You can't convert decimal to Hex (how would you deal with the fraction portion?). But you can use Int64 (a long) instead:

    var text = "101200001";
    var asLong = Convert.ToInt64(text);
    var asHex = asDecimal.ToString("X");
    

    asHex now has the hex string you're after.

    But the problem you have is that 'hex' is really just a way of viewing a set of raw bytes on disk. And the way a number is represented in raw bytes depends on the program itself. If you've got a binary writer, you just need to know the byte representation of the number you're trying to write. This may be enough by itself (without converting to string):

    bw.Write(asLong);
    

    Looked at this more, and it seems as though you're after 4-byte numbers, so ints not longs. BitConverter is good, but it writes everything in reverse order to what you may want. So keep these in mind and review the below:

    var text = "101200001";
    var asInt = Convert.ToInt32(text);                    // 4 byte number
    var asBytes = BitConverter.GetBytes(asInt).Reverse(); // same hex representation as a byte array (same order)
    

    And so in your example add this:

    bw.Write(asBytes);