【发布时间】:2016-01-18 23:03:46
【问题描述】:
我在一次读取 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);
}
【问题讨论】:
-
您检查过
<<和|运算符吗? -
我认为我们需要@unwind。这家伙正在投射 malloc 的返回值。
-
@PeterSchneider 虽然@unwind 不在这里:请不要投射
malloc()的结果。这样做是没有用的,并且可以隐藏错误。 -
@FUZxxl 哈!抓到一个!坡定律仍然有效!
-
这个问题没有意义,因为你没有提到数字存储在文件中的字节序,也没有提到处理器的字节序。不知道这两件事是不可能回答这个问题的。 (令人惊讶的是,人们仍然试图回答......)