so the following converts big endians to little ones
uint32_t ntoh32(uint32_t v)
{
return (v << 24)
| ((v & 0x0000ff00) << 8)
| ((v & 0x00ff0000) >> 8)
| (v >> 24);
}
works. like a charm.
I read 4 bytes from a big endian file into char v[4]
and pass it into the above function as
ntoh32 (* reinterpret_cast<uint32_t *> (v))
that doesn't work - because my compiler (VS 2005) automatically converts the big endian char[4] into a little endian uint32_t when I do the cast.
AFAIK, this automatic conversion will not be portable, so I use
uint32_t ntoh_4b(char v[])
{
uint32_t a = 0;
a |= (unsigned char)v[0];
a <<= 8;
a |= (unsigned char)v[1];
a <<= 8;
a |= (unsigned char)v[2];
a <<= 8;
a |= (unsigned char)v[3];
return a;
}
yes the (unsigned char)
is necessary.
yes it is dog slow.
there must be a better way. anyone ?