1

I want to extract an unsigned integer from a binary file.

Here is the code I wrote:

std::ifstream is(path, std::ios::in|std::ios::binary);

uint32_t count;
is.read((char*)&count, 4);

std::cout << count << std::endl;

The beginning of the file is 00 00 EA 60, and so I should get 60000.

Instead of that, I get 1625948160, which is 60 EA 00 00.

EDIT:

I am asking if there is a way to have the std::ifstream reverse the bytes itself, i.e. by reading the bytes in reverse order?

I find it overkill to reverse each integers afterward if there is a way to have them read backward from the start

Sinder
  • 273
  • 1
  • 11
  • 3
    Strange that you know enough to tag your question with `endianess` but don't know enough that this concept completely explains your issue. Reversing the bytes is what you have to do. – john Apr 07 '19 at 19:09
  • @john I am asking if there is a way to have the std::ifstream reverse the bytes itself, I.e. by reading the bytes in reverse order. I find it overkill to reverse each integers afterward if there is a way to have them read backward from the start – Sinder Apr 07 '19 at 20:17
  • @Sinder How would it know which bytes to reverse? Should it reverse the first two bytes? The first seven bytes? The first twenty three bytes? – David Schwartz Apr 07 '19 at 20:27
  • @Sinder No there is no way to make the ifstream reverse the bytes for you. – john Apr 07 '19 at 20:29
  • Ok I got your point. Thank you I will stick to the `ntohl()` function then – Sinder Apr 07 '19 at 20:51

0 Answers0