Home>

I'm making a hex dump and restoration tool in C.

  • Tool overview
    Function 1: Hexadecimal dump of input file (input.bin) and output to output file (output.txt).
    Function 2: Restores the input file (input.txt) and outputs it to the output file (output.bin).
    * If the contents of output.txt and intput.txt are the same, output.bin is the same as input.bin.

  • input.bin
    Consists of binary data (including text data).

  • output.txt
    The dump result is written in text format.
    Here, there is no address or space delimiter, and it is a file with only data (characters 0 to 9, A to F, a to f).

  • input.txt
    Same contents as output.txt.

  • output.bin
    Consists of binary data (including text data).

Error message

Function 1 is almost complete.
Function 2 can restore ASCII single-byte characters, but cannot restore Shift-JIS double-byte characters.
The code below restores a 2-byte hex character to a 2-byte character, but the result is

It has become.

Applicable source code
int main (void) {
    FILE * fo;
    char output [] = "output.bin";
    // file open
    if (fopen_s (&fo, output, "wb")! = 0) {// Open output file
        // Error if failed
    }
    char c [5] = "82A0";// 0x82A0 =>'Ah'
    long v = strtol (c, NULL, 16);
    fwrite (&v, 2, 1, fo);// Is this bad?
    // file close
    if (fclose (fo)! = 0) {// Close output file
        // Error if failed
    }
}

The debugger confirmed that the value of long v was 33,440 (0x82A0).
I think that the fwrite of the next line is not successful.

Supplemental information (FW/tool version etc.)

None

  • Answer # 1

    What is the environment?
    If it is now, Windows? Linux? Well, is the CPU Intel?

      

    The value of long v is 33,440 (0x82A0)

    is 4 bytes long and the internal representation (byte sequence) isA0 82 00 00,

      

    fwrite (&v, 2, 1, fo);// Is this bad?

    With

    , the first 2 bytes are output, and the file is 0xA0, 0x82.

      

    char c [5] = "82A0";// 0x82A0 =>'Ah'
          long v = strtol (c, NULL, 16);

    The conversion of multiple bytes together with

    is not bad, but I have a problem with the internal representation of integers, so I prefer one byte at a time.
    Think about the specific method.

    There are several ways. If you want a lot of code, you often use a table lookup on a 256-byte table.