簡體   English   中英

如何使用fstream將十六進制值讀取為整數(C ++)

[英]How to read hex values into integer with fstream (C++)

我正在嘗試從二進制文件中讀取一個Little-endian十六進制字符串,並將該值放入一個整數以使用它。 當我嘗試閱讀時,沒有得到數字,而是得到了ASCII符號。 我已經試過演員表和atoi,似乎沒有任何工作。 使用fstream從文件讀取十六進制字符串為整數的最佳方法是什么?

這本質上是我的程序:

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

int main(int argc, char* argv[]) {
    fstream input;
    fstream output;
    char cbuffer[4];
    char revbuffer[8];

    input.open(argv[1], fstream::binary | fstream::in);
    output.open("output.txt", ios::out | ios::app);
    input.seekg(16, input.beg);
    input.read(cbuffer, 4);

    cout << sizeof(revbuffer) << endl;
    cout << cbuffer[0] << cbuffer[1] << cbuffer[2] << cbuffer[3] << endl;
}

如果它是以二進制格式存儲的整數值,那么我猜它可能是int32_tuint32_t 由於您提到該值是以低位字節序存儲的,因此我想您要確保運行程序的主機將其轉換(如果需要)。 C ++ 20具有std :: endian 如果那對您不可用,那么通常可以使用一些宏來檢測編譯時的字節序,而不是我使用的std::endian測試。 我假設該值是下面的uint32_t

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <type_traits> // std::endian

// little endian unsigned 32 bit integer to host byte order
inline uint32_t Le32toh(uint32_t le) {
    #if __cplusplus <= 201703L
    // run-time check
    static constexpr uint16_t endian = 1;
    if(*reinterpret_cast<const uint8_t*>(&endian)==1) return le;
    #else
    // compile-time check
    static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
    if constexpr (std::endian::native == std::endian::little) return le;
    #endif

    const uint8_t* c=reinterpret_cast<const uint8_t*>(&le);
    return // little-to-big endian conversion
        (static_cast<uint32_t>(c[0])<<24) |
        (static_cast<uint32_t>(c[1])<<16) |
        (static_cast<uint32_t>(c[2])<<8) |
        (static_cast<uint32_t>(c[3]));

    return le;
}


int main(int argc, char* argv[]) {
    std::vector<std::string> args(argv+1, argv+argc);

    std::fstream output("output.txt", std::ios::out | std::ios::app);

    uint32_t cbuffer;

    for(const auto& file : args) {
        std::fstream input(file, std::fstream::binary | std::fstream::in);
        input.seekg(16, input.beg);
        // read directly into the varibles memory
        input.read(reinterpret_cast<char*>(&cbuffer), 4);
        // output the value unconverted
        std::cout << std::hex << cbuffer << "\n";
        // convert if needed
        cbuffer = Le32toh(cbuffer);
        // output the value converted
        std::cout << std::hex << cbuffer << "\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM