我在一次读取2个字节并将其转换为无符号的短大端元组时遇到问题。
这是我当前的代码,我想打印无符号的短大端,它应该是数字25。
所以这段代码是用来读取二进制文件的,我把所有文件保存到一个缓冲区,我需要缓冲区[5]和缓冲区[6]到无符号的短大端

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

最佳答案

以下代码将在big endian中从unsigned short创建buffer

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

关于c - 读取二进制文件,将2字节转换为无符号短C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33234082/

10-13 01:48