Native Endians and Auto Conversion
        Posted  
        
            by KnickerKicker
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by KnickerKicker
        
        
        
        Published on 2010-03-27T05:42:33Z
        Indexed on 
            2010/03/27
            5:53 UTC
        
        
        Read the original article
        Hit count: 305
        
endianness
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 ?
© Stack Overflow or respective owner