计算.txt文件中十六进制字符的频率

时间:2017-02-28 12:50:42

标签: c++ hex

我有一个包含以空格分隔的十六进制值的文件。我想找到每个十六进制值的频率并将其写入文本文件。例如,考虑字符串"1b 17 3c 45 3f 52 7a 5a 3b 45 31 52 2e 17 3e 58 3f 44 "。我想计算每个十六进制值的出现频率:

1b - 1 times 
17 - 2 times
.... so on.

我目前编写了一个c ++程序,但它也将十六进制字符之间的空间计为十六进制字符,并且不能按预期运行。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main() 
{
    int x  = 0;
    int total[128] = {0};
    int index;

    ifstream infile;
    ofstream outfile;

    infile.open("hex.txt");
    outfile.open("results2.txt");
    if(!infile)
    {
        cout << "Error opening input file" << endl;
        return 0;
    }   

    char c;
    while(infile.get(c))
    {
        index = c;
        total[index]++;
    } 

    for (int i=0; i<128; i++)      // Print the results
    {
        outfile << "  " << hex << i << " occurs "
                << setw(5) << dec << total[i] << " times" 
                << "  " << endl;
    }
    return 0;
}

注意:

"hex.txt" is the input file
"results2.txt" is the output file

1 个答案:

答案 0 :(得分:2)

只需将输入文件读为十六进制:

while(infile >> hex >> index)
{
    if (index < 0 || index >= 128) {   // ensure value is in array range...
        cerr << "Found an incorrect value " << hex << index << endl;
        return 1;
    }
    total[index]++;
}