nnn
nnn

Reputation: 41

convert from unsigned char array to long c

I read a long from a binary file into an unsigned char buffer using fread.

Now I would like to get the long. How do I do it?

unsigned char buffer[sizeof(long)];

fread(buffer, sizeof(long), 1, my_file);

thanks!

Upvotes: 4

Views: 1355

Answers (2)

Tenobaal
Tenobaal

Reputation: 835

If you are planning to transfer the file between machines, you need to do this:

// will swap the byte order in little endian and not in big endian
long transform_standart_byte_order(long in) {
    return (((unsigned long) ((char*) &in)[0] << 56) |
           (((unsigned long) ((char*) &in)[1] << 48) |
           (((unsigned long) ((char*) &in)[2] << 40) |
           (((unsigned long) ((char*) &in)[3] << 32) |
           (((unsigned long) ((char*) &in)[4] << 24) |
           (((unsigned long) ((char*) &in)[5] << 16) |
           (((unsigned long) ((char*) &in)[6] <<  8) |
           (((unsigned long) ((char*) &in)[7]);
}

void write_long(FILE* my_file, long val) {
    val = transform_standart_byte_order(val);
    fwrite(val, sizeof(val), 1, my_file);
}

long read_long(FILE* my_file) {
    long val;
    fread(&val, sizeof(val), 1, my_file);
    return transform_standart_byte_order(val);
}

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613461

Surely you mean:

long buffer;
fread(&buffer, sizeof(long), 1, my_file);

Upvotes: 2

Related Questions