简体   繁体   中英

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!

Surely you mean:

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

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);
}

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