读取文件十六进制数据并以c ++格式存储到字符串2d数组中

时间:2015-02-24 12:25:21

标签: c++ visual-c++ hex

我有" hex.txt"文件。这是一些数据:

  

gdujdurkndvju; roaen' pefk' ojfsbfwh

     

dusigfluyfygrleuieubhfl; wieeufhrr

     

ygilrfreusov' rpgtgtgt [S' rgjhery48

我需要将其读作十六进制并将其存储为字符串2d数组(16列)。

  

示例:

     

67 64 75 6A 64 75 72 6B 6E 64 76 6A 75 3B 72 6F

     

61 65 6E 27 70 65 66 6B 27 6F 6A 66 73 62 66 77

     

68 0D 0A 64 75 73 69 67 66 6C 75 79 66 79 67 72

     

6C 65 75 69 65 75 62 68 66 6C 3B 77 69 65 65 75

     

66 68 72 72 0D 0A 79 67 69 6C 72 66 72 65 75 73

     

6F 76 27 72 70 67 74 67 74 67 74 5B 73 27 72 67

     

6A 68 65 72 79 34 38

这是我试过的代码。我需要帮助才能完成此代码。

unsigned char hx;
int main()
{
ifstream data("hex.txt", std::ios::binary);
data >> std::noskipws;
while (data >> hx) {
    std::cout << std::hex <<std::setw(2)<< std::setfill('0') << (int)hx<<" ";
}
return 0;
}

2 个答案:

答案 0 :(得分:0)

我将字节写入一维数组以避免平方运行时。您可以使用已定义的行将其解释为矩阵。我可以将其用于输出。

#include <iostream>
#include <stdio.h>
#include <fstream>

int main(int argc, char** argv){
    std::ifstream data("hex.txt", std::ios::binary | std::ios::ate);    
    data >> std::noskipws;

    int filesize = data.tellg(); //getting filesize in byte
    data.seekg(0); //setting the cursor back to the beginning of the file

    char* filebytes = new char[filesize];

    char currentByte;   
    int rowWidth = 16;
    int cCol = 0;
    while (!data.eof()) {
        data.get(currentByte);

        std::cout << std::hex << (int)currentByte << " ";
        filebytes[cCol] = currentByte;

        cCol++;
        if(cCol > 0 && cCol % rowWidth == 0){
            std::cout << std::endl;
        }

    }
    data.close();

    return 0;
}

我希望这是你想要做的。

答案 1 :(得分:0)

好的,现在尝试使用std :: string和std :: stringbstream

#include <iostream>
#include <stdio.h>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>

int main(int argc, char** argv){
    std::ifstream data("hex.txt", std::ios::binary | std::ios::ate);    
    data >> std::noskipws;

    int filesize = data.tellg();
    data.seekg(0);

    // array of strings containing outputformated bytes
    std::string* filebytes = new std::string[filesize];

    char currentByte;   
    int rowWidth = 16;
    int idx = 0;
    while (idx < filesize && !data.eof()) {
        data.get(currentByte);

        // buffers strings to concatenate outputformat
        std::stringstream ss;
        ss << std::hex << std::setw(2)<< std::setfill('0') << (int)currentByte;
        // putting strings into the string array
        filebytes[idx] = ss.str();

        idx++;
    }
    data.close();

    //output to debug
    for(idx = 0; idx < filesize; idx++){
        std::cout << filebytes[idx] << " ";

        if(idx > 0 && idx % rowWidth == 0){
            std::cout << std::endl;
        }
    }

    return 0;
}

愿这就是你要找的。

相关问题