我在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);
}
答案 0 :(得分:2)
以下代码将从大端的unsigned short
创建buffer
:
unsigned short us = (buffer[5] << 8) | buffer[6];
答案 1 :(得分:0)
假设 -
你需要 -
uint16_t half_word = ((uint8_t)buffer[5] << 8) | ((uint8_t)buffer[6])
P.S。 -
uint8_t *buffer
代替char *buffer
来避免对类型转换缓冲区八位字节的需要。
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;