简体   繁体   中英

c++ creating 4 integer from the 16 byte char array

Here is my question

I've read a binary sequence from a binary file into a char array. My binary file is much bigger than my buffer so, I've read it iteratively.

I've read 16 Bytes from the file and store it into char * myPointer pointer. Now from myPointer I need to create 4 integer and I dont know how could I do that. Is there anyone to help me ?

Note: I dont have to store it into char array if you have better solution

If endianess of stored data is same as endianess of your system, then you can use following code to store read data in int :

int ints[4];
char bytes[4*sizeof(int)];
memcpy( ints, bytes, sizeof( ints ) );

If you have different endianess in input binary file and on your computer, you might want to swap the bits:

template< class T>
void changeEndianess( T & input)
{
    char temp[ sizeof( T ) ];
    for( int j=sizeof( T )-1; j>=0; --j )
        temp[sizeof(T)-j-1] = *((char *)&input+j);
    memcpy( &input, temp, sizeof( T ) );
}

// and somewhere in your program:
for( size_t i=0; i<sizeof( ints ); ++i )
{
    changeEndianess<int>( ints[i] );
}

To make it use short change all int in above code to short , but it's up to you to decide when it is needed.

Reading from a binary file:

#include <fstream>
#include <assert.h>

void main()
{
    std::ifstream file("file.dat", std::ios_base::binary);
    assert(file.is_open());

    int i = 0;
    file.read((void*)&i, sizeof(i));
    short s = 0;
    file.read((void*)&s, sizeof(s));

    ... // And so on
}

Obviously, you need to know exactly how to interpret the data, ie the file structure (which data type is written where).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM