On 6/6/05, Segher Boessenkool <[EMAIL PROTECTED]> wrote:
> > There's also a fair amount of code whih relies on -1 ==
> > (int)0xFFFFFFFF.
> >
> > Or is there any truly portable and efficient way to convert a sequence
> > of bytes (in big-endian order) to a signed integer?
> 
> Of course there is.  Assuming no padding bits:

[snip complicated stuff]

Better use a union for the (final) conversion, i.e

int conv(unsigned char *c)
{
    unsigned int i;
    union {
        unsigned int u;
        int i;
    } u;

    u.u = 0;
    for (i = 0; i < sizeof u; i++)
      u.u = (u.u << 8) + c[i];

    return u.i;
}

or even (if you can determine native byte-order and size at compile time)

int conv(unsigned char *c)
{
   union {
      unsigned char c[4];
      int i;
   } x;
   int i;
   for (int i=0; i<4; ++i)
      x.c[3-i] = c[i];
   return x.i;
}

which generates only slightly worse code than above.

Richard.

Reply via email to