Opa114
Opa114

Reputation: 548

C++ How to read Bytes as Integer endianness independent?

i want to read some Bytes of my File as an Integer Value. For Example the file contains the value 0x000003BB which equals 955.

I could read the data this way:

ifstream input ("C:/Desktop/myFile", ios::binary);
uint8_t buffer[4] = {0};
input.read((char*)buffer, sizeof(buffer));

But how can i convert the buffer-array to the corresponding int-value 955? And if possible in a endianness independent way, because this and some other Files in Big Endian Byte Order but my system are on Little Endian Byte Order. Thanks :)

Upvotes: 2

Views: 4843

Answers (3)

petrmikheev
petrmikheev

Reputation: 342

I am not sure that this is the best solution, but it works.

uint8_t buffer[4] = {0};
input.read((char*)buffer, sizeof(buffer));
unsigned int result = buffer[0];
result = (result << 8) | buffer[1];
result = (result << 8) | buffer[2];
result = (result << 8) | buffer[3];

Upvotes: 3

Ajay
Ajay

Reputation: 18411

There is no need to use an array of uint8_t, you can direcly read into a 4 byte integer:

uint32_t data;
input.read((char*)&data, sizeof(data));

EDIT:

This code works on my VC++ compiler:

#include<stdint.h>
#include<intrin.h>
#include<iostream>

int main()
{
    uint32_t data;
    data = 0xBB030000;
    data = _byteswap_ulong(data);

    std::cout << data;
}

If you are using GCC, you need to replace _byteswap_ulong with __builtin_bswap32. If you need independent code, you need to craft your own (probably on top of these compiler intrinsics).

Upvotes: 1

eerorika
eerorika

Reputation: 238291

If your OS supports POSIX or is windows, then you can use ntohl:

int data;
input >> data;
data = ntohl(data);

Upvotes: 2

Related Questions