Hello to the forum, perhaps someone can help me. I am trying to read a file that has the following format:

128 byte header
float data

When reading the header, I need to extract the following from the header:
bytes0-6= short unsigned int big endian
byte7 = int

bytes8-23= float little endian
byte24= int

so here is what I have done:

short max_x, max_y, max_z;

fread(&max_z, sizeof(short), 1, fp);
fread(&max_y, sizeof(short), 1, fp);
fread(&max_x, sizeof(short), 1, fp);

Given that the first four values in the header are 100, 100, 100, 1, when I check what have for max_x, max_y, max_z, I should get 100, 100, 100, however


gives me 25600 for each.

Am i messing up the printf, or is there something else I need to do in order to read the data properly. Thank you!

Recommended Answers

All 4 Replies

Seems like your reading big-endian data into a little-endian value. You'll need to endian swap the bigs to littles.

>>bytes0-6= short unsigned int big endian
are you sure that's right? 0-6 is 7 bytes and sizeof(short) is only 2 bytes on most 32-bit compilers.

>>byte7 = int
No it isn't -- sizeof(int) on 32-bit compilers is 4 bytes. 1 byte is just a char.

>>bytes8-23= float little endian
sizeof(float) is not 16 bytes but only 4 bytes. Maybe you mean that contains 4 float values ?

Run the below to verify size of data on your machine

#include <iostream>
using namespace std;

int main(int argc,char* argv[])
    cout << "sizeof(sort) = " << sizeof(short) << "\n";

    cout << "sizeof(float) = " << sizeof(float) << "\n";
    cout << "sizeof(double) = " << sizeof(double) << "\n";
	return 0;

Since we are in the C forum.

 *  sizeof.c
 *  Finding the size of some type
#include <stdio.h>

int main ( void )
    printf( "\nsizeof ( short ) occupy %d bytes", sizeof ( short ) );
    printf( "\nsizeof ( float ) occupy %d bytes", sizeof ( float ) );
    printf( "\nsizeof ( double ) occupy %d bytes", sizeof ( double ) );
    return 0;
commented: you are right -- thanks for the correction +20

Thank you Ancient Dragon for the corrections, I should have paid more attention to what I was writing. Basically the header contains four unsigned short ints, (number of pixels in four dimensions), four float values, (physical sizes of the four dimensions), then finally a flag indicating whether pixel data is float or double. The rest of the header contains information not needed by us.

Yes the four unsigned shorts are in big endian, while the rest is little. A simple byte swap fixed that. Thank you for your response though!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.