将文件内容转换为十六进制格式

时间:2012-05-31 08:05:12

标签: c hex decimal

这里我有一个文件testdec.txt。 在此文件内容如下所示。

N = 162,27,79,83,101,69,213,78,188,215,254,75,222,74,204,124,53,108,240,157,213,109,189,143,226,71,120,134,57,27,64,230,126,218,4,249,150,44,182,223,70,241,96,113,61,115,54,13,209,53,236,157,164,126,202,150,121,13,180,223,50,84,239,39,188,44,119,71,50,220,196,107,218,66,106,24,203,13,150,135,231,65,240,236,32,226,166,2,243,26,236,253,185,88,196,58,255,146,93,202,57,219,57,160,62,160,225,167,0,209,231,110,156,106,8,119,47,255,46,87,76,10,243,99,48,147,47,197
E = 1,0,1 

这里我想以十六进制格式转换N and E值,并希望将每个十进制值写成两个十六进制值的字节,而不是comma分隔符。我想在另一个testhex.txt文件中写这个十六进制值。

如果十进制值只是十六进制的一个字节,那么我必须在该十六进制值的前面添加0。 你可以在E的价值中看到这件事。

我想在其他文件或同一文件中执行所有这些操作。可能在另一个文件中是可能的。我们不能在同一个文件中做。

我想要另一个testhex.txt文件输出文件,如

N = A21B4F536545D54EBCD7FE4BDE4ACC7C356CF09DD56DBD8FE2477886391B40E67EDA04F9962CB6DF46F160713D73360DD135EC9DA47ECA96790DB4DF3254EF27BC2C774732DCC46BDA426A18CB0D9687E741F0EC20E2A602F31AECFDB958C43AFF925DCA39DB39A03EA0E1A700D1E76E9C6A08772FFF2E574C0AF36330932FC5
E = 010001

那我怎样才能实现这个目标。请给我一些建议。

编辑:尝试使用此testdec.txt根据BLUEPIXY代码,它会无限循环。

N = 137,72,247,73,196,168,11,223,107,232,230,189,125,211,175,123,12,235,2,231,123,244,84,184,214,143,144,189,38,103,237,173,129,68,158,92,8,141,76,60,76,98,54,39,7,48,148,45,76,105,52,191,255,245,117,156,25,122,244,65,79,110,244,17,23,110,128,239,117,70,46,140,178,75,230,126,242,100,77,194,42,187,241,110,218,215,242,118,186,92,133,26,175,167,158,16,113,123,105,114,161,23,79,197,76,102,103,93,230,174,120,128,194,34,104,42,253,131,122,49,30,212,205,237,119,71,108,95
E = 1,0,1 
N = 137,72,247,73,196,168,18,223,107,232,230,189,125,211,175,123,12,235,2,231,123,244,84,184,214,143,144,189,38,103,237,173,129,68,158,92,8,141,76,60,76,98,54,39,7,48,148,45,76,105,52,191,255,245,117,156,25,122,244,65,79,110,244,17,23,110,128,239,117,70,46,140,178,75,230,126,242,100,77,194,42,187,241,110,218,215,242,118,186,92,133,26,175,167,158,16,113,123,105,114,161,23,79,197,76,102,103,93,230,174,120,128,194,34,104,42,253,131,122,49,30,212,205,237,119,71,108,95
E = 1,0,1 

2 个答案:

答案 0 :(得分:1)

一个样本

#include <stdio.h>

int main(){
    FILE *fin,*fout;
    char ch1,ch2;
    int data;

    fin=fopen("testdec.txt", "r");
    fout=fopen("testhex.txt", "w");
    while(1){
        if(EOF==fscanf(fin, "%c %c ", &ch1, &ch2))
            break;
        fprintf(fout, "%c %c ", ch1, ch2);
        while(EOF!=fscanf(fin, "%d%c%*[ \n]", &data, &ch1)){
            fprintf(fout, "%02X", data);
            if(ch1 == ',') continue;
            if(ch1 == '\n' || ch1 == ' '){
                fprintf(fout, "\n");
                break;
            }
        }
    }
    fclose(fout);fclose(fin);
    return 0;
}

答案 1 :(得分:0)

你试过了吗?

  • man fgets,它会从文件中读取行。
  • man strtok,它提取以分隔符分隔的数据。
  • man atoi,将字符串转换为int。
  • man fprintf,这会将int值作为十六进制字符串写入文件。