二进制文件读取,将2个字节转换为无符号短C

时间:2015-10-20 10:21:58

标签: c binary unsigned short

我在onces上读取2个字节时遇到问题,并将其转换为unsigned short,big endian。

这是我目前的代码,我想打印未签名的短大端,也应该是25号。

所以这段代码用于读取二进制文件,我将所有文件保存到缓冲区,我需要缓冲区[5]和缓冲区[6]到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);
    }

2 个答案:

答案 0 :(得分:2)

以下代码将从大端的unsigned short创建buffer

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

答案 1 :(得分:0)

假设 -

  1. 您正在使用支持C99和
  2. 的编译器
  3. 文件中的数据按网络字节顺序
  4. 你需要 -

    uint16_t half_word = ((uint8_t)buffer[5] << 8) | ((uint8_t)buffer[6])
    

    P.S。 -

相关问题