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











up vote
0
down vote

favorite












I am trying to read a little-endian hex string from a binary file, and put that value into an integer to work with it. When I try to read, instead of getting a number I get ascii symbols. I've tried casts and atoi and nothing seems to work. What is the best way to use fstream to read a hex string into an integer from a file?



This is essentially my program:



#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;
}









share|improve this question









New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • is the value really stored as a hex string in the file? You mentioned the byte order and you read 4 chars from the file so a hex string seems improbable.
    – Ted Lyngmo
    1 hour ago

















up vote
0
down vote

favorite












I am trying to read a little-endian hex string from a binary file, and put that value into an integer to work with it. When I try to read, instead of getting a number I get ascii symbols. I've tried casts and atoi and nothing seems to work. What is the best way to use fstream to read a hex string into an integer from a file?



This is essentially my program:



#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;
}









share|improve this question









New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • is the value really stored as a hex string in the file? You mentioned the byte order and you read 4 chars from the file so a hex string seems improbable.
    – Ted Lyngmo
    1 hour ago















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am trying to read a little-endian hex string from a binary file, and put that value into an integer to work with it. When I try to read, instead of getting a number I get ascii symbols. I've tried casts and atoi and nothing seems to work. What is the best way to use fstream to read a hex string into an integer from a file?



This is essentially my program:



#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;
}









share|improve this question









New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I am trying to read a little-endian hex string from a binary file, and put that value into an integer to work with it. When I try to read, instead of getting a number I get ascii symbols. I've tried casts and atoi and nothing seems to work. What is the best way to use fstream to read a hex string into an integer from a file?



This is essentially my program:



#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;
}






c++ input hex fstream atoi






share|improve this question









New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 3 hours ago









dwalter

5,35912233




5,35912233






New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 4 hours ago









Kasper

1




1




New contributor




Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Kasper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • is the value really stored as a hex string in the file? You mentioned the byte order and you read 4 chars from the file so a hex string seems improbable.
    – Ted Lyngmo
    1 hour ago




















  • is the value really stored as a hex string in the file? You mentioned the byte order and you read 4 chars from the file so a hex string seems improbable.
    – Ted Lyngmo
    1 hour ago


















is the value really stored as a hex string in the file? You mentioned the byte order and you read 4 chars from the file so a hex string seems improbable.
– Ted Lyngmo
1 hour ago






is the value really stored as a hex string in the file? You mentioned the byte order and you read 4 chars from the file so a hex string seems improbable.
– Ted Lyngmo
1 hour ago














1 Answer
1






active

oldest

votes

















up vote
0
down vote













If it's an integer value stored in binary format, I guess it's either a int32_t or a uint32_t. Since you mention that the value is stored in little-endian byte order, I guess you want to make sure that the host running your program converts it (if it needs to). C++20 has std::endian. If that's not available to you, there are usually macros for detecting endianness at compiletime that you can use instead of the std::endian tests I've used. I've assumed that the value is a uint32_t below.



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

// little endian unsigned 32 bit to host byte order
inline uint32_t Le32toh(uint32_t le) {
static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
if constexpr (std::endian::native == std::endian::little) return le;
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";
}
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    Kasper is a new contributor. Be nice, and check out our Code of Conduct.










     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371469%2fhow-to-read-hex-values-into-integer-with-fstream-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    If it's an integer value stored in binary format, I guess it's either a int32_t or a uint32_t. Since you mention that the value is stored in little-endian byte order, I guess you want to make sure that the host running your program converts it (if it needs to). C++20 has std::endian. If that's not available to you, there are usually macros for detecting endianness at compiletime that you can use instead of the std::endian tests I've used. I've assumed that the value is a uint32_t below.



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

    // little endian unsigned 32 bit to host byte order
    inline uint32_t Le32toh(uint32_t le) {
    static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
    if constexpr (std::endian::native == std::endian::little) return le;
    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";
    }
    }





    share|improve this answer



























      up vote
      0
      down vote













      If it's an integer value stored in binary format, I guess it's either a int32_t or a uint32_t. Since you mention that the value is stored in little-endian byte order, I guess you want to make sure that the host running your program converts it (if it needs to). C++20 has std::endian. If that's not available to you, there are usually macros for detecting endianness at compiletime that you can use instead of the std::endian tests I've used. I've assumed that the value is a uint32_t below.



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

      // little endian unsigned 32 bit to host byte order
      inline uint32_t Le32toh(uint32_t le) {
      static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
      if constexpr (std::endian::native == std::endian::little) return le;
      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";
      }
      }





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        If it's an integer value stored in binary format, I guess it's either a int32_t or a uint32_t. Since you mention that the value is stored in little-endian byte order, I guess you want to make sure that the host running your program converts it (if it needs to). C++20 has std::endian. If that's not available to you, there are usually macros for detecting endianness at compiletime that you can use instead of the std::endian tests I've used. I've assumed that the value is a uint32_t below.



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

        // little endian unsigned 32 bit to host byte order
        inline uint32_t Le32toh(uint32_t le) {
        static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
        if constexpr (std::endian::native == std::endian::little) return le;
        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";
        }
        }





        share|improve this answer














        If it's an integer value stored in binary format, I guess it's either a int32_t or a uint32_t. Since you mention that the value is stored in little-endian byte order, I guess you want to make sure that the host running your program converts it (if it needs to). C++20 has std::endian. If that's not available to you, there are usually macros for detecting endianness at compiletime that you can use instead of the std::endian tests I've used. I've assumed that the value is a uint32_t below.



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

        // little endian unsigned 32 bit to host byte order
        inline uint32_t Le32toh(uint32_t le) {
        static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
        if constexpr (std::endian::native == std::endian::little) return le;
        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";
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 2 hours ago

























        answered 4 hours ago









        Ted Lyngmo

        838112




        838112






















            Kasper is a new contributor. Be nice, and check out our Code of Conduct.










             

            draft saved


            draft discarded


















            Kasper is a new contributor. Be nice, and check out our Code of Conduct.













            Kasper is a new contributor. Be nice, and check out our Code of Conduct.












            Kasper is a new contributor. Be nice, and check out our Code of Conduct.















             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371469%2fhow-to-read-hex-values-into-integer-with-fstream-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            'app-layout' is not a known element: how to share Component with different Modules