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
























  • 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
    Nov 19 at 11:39












  • Maybe not then, I don't really know how to call it. I'm fairly new to programming. The value is at offset 0x10 and looks something like [in hex] 00 92 f8 03. The number should read 0x03f89200.
    – Kasper
    Nov 19 at 22:41















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
























  • 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
    Nov 19 at 11:39












  • Maybe not then, I don't really know how to call it. I'm fairly new to programming. The value is at offset 0x10 and looks something like [in hex] 00 92 f8 03. The number should read 0x03f89200.
    – Kasper
    Nov 19 at 22:41













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















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















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 9:42









dwalter

5,38912233




5,38912233










asked Nov 19 at 9:16









Kasper

31




31












  • 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
    Nov 19 at 11:39












  • Maybe not then, I don't really know how to call it. I'm fairly new to programming. The value is at offset 0x10 and looks something like [in hex] 00 92 f8 03. The number should read 0x03f89200.
    – Kasper
    Nov 19 at 22:41


















  • 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
    Nov 19 at 11:39












  • Maybe not then, I don't really know how to call it. I'm fairly new to programming. The value is at offset 0x10 and looks something like [in hex] 00 92 f8 03. The number should read 0x03f89200.
    – Kasper
    Nov 19 at 22:41
















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
Nov 19 at 11:39






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
Nov 19 at 11:39














Maybe not then, I don't really know how to call it. I'm fairly new to programming. The value is at offset 0x10 and looks something like [in hex] 00 92 f8 03. The number should read 0x03f89200.
– Kasper
Nov 19 at 22:41




Maybe not then, I don't really know how to call it. I'm fairly new to programming. The value is at offset 0x10 and looks something like [in hex] 00 92 f8 03. The number should read 0x03f89200.
– Kasper
Nov 19 at 22:41












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










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





share|improve this answer























  • Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
    – Kasper
    Nov 19 at 22:54












  • Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
    – Ted Lyngmo
    Nov 20 at 0:20











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


}
});














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



accepted










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





share|improve this answer























  • Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
    – Kasper
    Nov 19 at 22:54












  • Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
    – Ted Lyngmo
    Nov 20 at 0:20















up vote
0
down vote



accepted










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





share|improve this answer























  • Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
    – Kasper
    Nov 19 at 22:54












  • Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
    – Ted Lyngmo
    Nov 20 at 0:20













up vote
0
down vote



accepted







up vote
0
down vote



accepted






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





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






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 at 0:21

























answered Nov 19 at 9:34









Ted Lyngmo

1,298214




1,298214












  • Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
    – Kasper
    Nov 19 at 22:54












  • Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
    – Ted Lyngmo
    Nov 20 at 0:20


















  • Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
    – Kasper
    Nov 19 at 22:54












  • Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
    – Ted Lyngmo
    Nov 20 at 0:20
















Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
– Kasper
Nov 19 at 22:54






Thanks for the reply. I'm getting an error: 'std::endian' has not been declared. But with main alone I'm now able to read the value as an int. Thanks very much!
– Kasper
Nov 19 at 22:54














Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
– Ted Lyngmo
Nov 20 at 0:20




Great! Yes, std::endian is a C++20 feature so to be able to do something similar during compile time in C++17 and earlier you'd have to resort to some non-standard endian macro - or do a runtime check. I'll add that too.
– Ted Lyngmo
Nov 20 at 0:20


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




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

"Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

Alcedinidae

Origin of the phrase “under your belt”?