简体   繁体   English

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

[英]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. 我一次读取2个字节并将其转换为无符号的短大字节序时遇到问题。

This is my current code, I want to print the unsigned short big endian as well, and it should be the number 25. 这是我当前的代码,我也想打印无符号的短大字节序,它应该是数字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 因此,此代码用于读取二进制文件,我将所有文件保存到缓冲区中,并且需要将buffer [5]和buffer [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中从buffer创建一个unsigned short

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

Assuming - 假设 -

  1. you are using a compiler which supports C99, and 您正在使用支持C99的编译器,并且
  2. the data in the file is in network byte order 文件中的数据按网络字节顺序

You need - 你需要 -

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

PS - PS-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM