Search code examples
cbinaryunsignedshort

Binary file reading, convert 2 bytes to an unsigned short C


I have a problem with reading 2 bytes at onces and convert it to an unsigned short, big endian.

This is my current code, I want to print the unsigned short big endian as well, and it should be the number 25.

So this code is for reading a binary file, I saved all the files to a buffer, and I need buffer[5] and buffer[6] to the unsigned short, big endian

void read_binair(const char* filename)
    {
        FILE *file;
        char *buffer;
        unsigned long fileLen;
        int i;
        char character;
        Level* level = level_alloc_empty();

        file = fopen(filename, "rb");
        if (!file)
        {
            fprintf(stderr, "Unable to open file %s", filename);
            return;
        }



        fseek(file, 0, SEEK_END);
        fileLen = ftell(file);
        fseek(file, 0, SEEK_SET);


        buffer = (char *)malloc(fileLen + 1);
        if (!buffer)
        {
            fprintf(stderr, "Memory error!");
            fclose(file);
            return;
        }



        fread(buffer, fileLen, 1, file);
        for (i = 0; i < 4; i++) 
        {   
            printf("%c", (char) buffer[i]);
        }
        i = buffer[4];
        printf("%d", i);
        //read buffer[5] and buffer[6] together as a unsigned short, big endian
        fclose(file);
    }

Solution

  • The following code will create an unsigned short from buffer in big endian:

    unsigned short us = (buffer[5] << 8) | buffer[6];