Mail Archives: djgpp/2000/04/25/08:14:29
Ben Alford <benjamin DOT alford AT surrey DOT uni DOT ntl DOT com> wrote:
> Hi
> I am trying to read data from a file. The file is in binary format. The data
> is either 1,2 or 4 bytes.
> I need to convert the byte information into an integer value.
Why convert? Integers are written as bytes, so you can always read
them back in the same way. No conversion is needed. At least as long
as you're using the same platform (CPU type, compiler, maybe mode of
operation of the CPU). If you want portability across platforms,
binary files are evil, anyway.
Just
#include <stdio.h>
#include <assert.h>
#include <limits.h>
short result;
FILE *some_file; /* opened and positioned already...*/
assert((sizeof(result)==2) && (CHAR_BIT == 8));
fread(&result, sizeof(result), 1, some_file);
and that's it. For this to work, the assertions have to be true,
that's why I wrote them down, in the code. On a system where 'short
int' doesn't have 16 bits, the call would return an error.
--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.
- Raw text -