C_C++

(C++) 이진파일을 16진수로 출력하기

고니자니 2024. 6. 11. 06:37
반응형

C++에서 이진파일을 16진수로 출력하려면, 파일을 읽어 각 바이트를 16진수로 변환하여 출력해야 합니다.

다음은 이를 수행하는 예제 코드입니다.

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
    ifstream inputFile("d:\\samples\\alarm01.wav", ios::binary);
    
    if (!inputFile) {
        cerr << "파일을 열 수 없습니다." << endl;
        return 1;
    }

    // 파일 끝까지 읽어들입니다.
    unsigned char byte;
    int count = 0;

    while (inputFile.read(reinterpret_cast<char*>(&byte), sizeof(byte))) {
        // 16진수로 출력
        cout << hex << setw(2) << std::setfill('0') << static_cast<int>(byte) << " ";
        count++;
        
        // 16바이트마다 줄 바꿈
        if (count % 16 == 0) {
            cout << endl;
        }
    }

    if (count % 16 != 0) {
        cout << endl;
    }

    inputFile.close();
    return 0;
}

(C++) 이진파일을 16진수로 출력하기

728x90
반응형