如何从文本文件转换十六进制数据并正确地将二进制代码写入可删除文件?

时间:2017-11-11 10:38:53

标签: c

如何将十六进制的PE格式(例如“d43c23F1”)转换为二进制。

我使用http://tomeko.net/online_tools/hex_to_file.php?lang=en,所有字符都在成功之外。

但使用C ++程序代码失败。

我的hex文件代码,代码是C程序中的“hello world”:

4D5A90000300000004000000FFFF0000 B8000000000000004000000000000000 00000000000000000000000000000000 000000000000000000000000F0000000 0E1FBA0E00B409CD21B8014CCD215468 69732070726F6772616D2063616E6E6F 742062652072756E20696E20444F5320 6D6F64652E0D0D0A2400000000000000 D80EC51B9C6FAB489C6FAB489C6FAB48 我的C程序代码:

#include "stdafx.h"
#include "StdAfx.h"
#include <stdlib.h>  
#include <string>  

int hex_to_int(char c)
{
    if (c >= 97)
        c = c - 32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first * 10 + second;
    if (result > 9) result--;
    return result;
}

int hex_to_ascii(char c, char d) {
    int high = hex_to_int(c) * 16;
    int low = hex_to_int(d);
    return high + low;
}

int main()
{
    char str[16];
    // open file
    FILE* file = fopen("D:\\outside.exe", "a+");
    FILE *fp = fopen("D:/hex.txt", "rb+");
    fseek(fp, 0, SEEK_END);
    int fileLen = ftell(fp);
    char *tmp = (char *)malloc(sizeof(char) * fileLen);
    fseek(fp, 0, SEEK_SET);
    fread(tmp, fileLen, sizeof(char), fp);
    int length = strlen(tmp);
    int i;
    char buf = 0;
    for (i = 0; i < fileLen; i++) {
        if (i % 2 != 0) {
            printf("%c", hex_to_ascii(buf, tmp[i]));
            // result string to tmp 
            sprintf(str, "%c", hex_to_ascii(buf, tmp[i]));
            // to file end
            fseek(file, 0, SEEK_END);
            // if str  == '\0' , no data write to file
            fwrite(str, sizeof(char), 1, file);
        }
        else {
            buf = tmp[i];
        }
    }
    fclose(file);
    free(tmp);
    return 0;
}

比较二进制结果,对比度是由于 0D0D

的处理不当造成的

如何解决?图片是比较结果

enter image description here

0 个答案:

没有答案