Re: Reading little-endian data from a file in a portable manner



Malcolm McLean wrote:
On Jul 16, 6:07 pm, Ben Bacarisse <ben.use...@xxxxxxxxx> wrote:
Malcolm McLean <malcolm.mcle...@xxxxxxxxxxxxxx> writes:

int x;
x = fgetc(fp);
x |= (fgetc(fp) << 8);
This, too can be UB if fgetc(fp) times 256 is not representable as an
int (and this is the usual case on a 16-bit machine). Again, if you use
unsigned types the problem goes away.

Except it doesn't, because on that architecture the routine will break
when you convert the unsigned to a signed.

The only way I can see of doing it is to manually apply 2s complement
conversion on an unsigned. Which isn't really acceptable.

In the grand scheme of portable data transfer, one must specify the encoding of data in the file. Can there be negative values? If so, how are they encoded? There are more than way. Pick one, then ensure that code that writes encodes properly and code that reads decodes properly.

--
Thad
.



Relevant Pages

  • Re: 32 or 64 bit processor info in C
    ... Malcolm McLean wrote, On 21/04/07 17:45: ... I suppose Malcolm might be happy with an int larger than the address bus by a few bits. ... > so it makes sense to use the same registers to hold pointers ...
    (comp.lang.c)
  • Re: When to check the return value of malloc
    ... Malcolm McLean wrote, On 19/01/08 13:51: ... this problem of too much error-handling code which will never be executed. ... it uses 'int' for the allocation size. ... It means again that your function is NOT a general purpose malloc wrapper and not suitable for use by a lot of people. ...
    (comp.lang.c)
  • Re: prob with int**
    ... Malcolm McLean wrote, On 21/09/08 16:54: ... int** for reperesentation of matrices(as double subscripted ... arrays .)but at run time an error occurs ..saying ...general exception ...
    (comp.lang.c)
  • Re: 32 or 64 bit processor info in C
    ... Malcolm McLean wrote: ... registers, so it makes sense to use the same registers to hold pointers ... clusters all use int of 32 bits. ...
    (comp.lang.c)
  • Re: *generic* pointer to function(s)?
    ... Malcolm McLean wrote, On 04/12/07 22:06: ... and deciding, by setting a pointer, which of them to use later in the ... int f1; ... char* f2; ...
    (comp.lang.c)