[英]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 - 假设 -
You need - 你需要 -
uint16_t half_word = ((uint8_t)buffer[5] << 8) | ((uint8_t)buffer[6])
PS - PS-
uint8_t *buffer
instead of char *buffer
to obviate the need for typecasting buffer octets. uint8_t *buffer
代替char *buffer
可以避免类型转换缓冲区八位字节的需要。
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.