Re: [linux-audio-dev] help with bigendian unsigned long long

New Message Reply About this list Date view Thread view Subject view Author view Other groups

Subject: Re: [linux-audio-dev] help with bigendian unsigned long long
From: Erik de Castro Lopo (erikd-lad_AT_mega-nerd.com)
Date: Thu May 09 2002 - 11:59:05 EEST


On Wed, 8 May 2002 19:24:55 -0400
Paul Davis <pbd_AT_op.net> wrote:

> i am reading a little endian unsigned long long (64 bit integer) as
> two LE 32 bit units. i know how to do this on a LE host. can someone
> tell me how to byte swap and OR them together to form the correct
> value if the host is bigendian?

Working and tested (x86 Linux and Sparc Solaris) code:

-------------------------------------------------------------------------
#include <stdio.h>

#ifdef __linux__
    #include <endian.h>
#elif defined (__sparc__)
    #define LITTLE_ENDIAN 0
    #define BIG_ENDIAN 1
    #define BYTE_ORDER BIG_ENDIAN
#else
    #error "AAARrrrrgggggh"
#endif

typedef unsigned long long u_int64_t ;
typedef unsigned int u_int32_t ;

u_int64_t
endswap_u_int64 (u_int64_t val)
{ unsigned char *cptr ;
    u_int32_t temp ;
    u_int64_t newval ;

    cptr = (char*)(&newval) ;

    if (BYTE_ORDER == LITTLE_ENDIAN)
    { temp = val ;
        cptr [7] = temp ;
        cptr [6] = temp >> 8 ;
        cptr [5] = temp >> 16 ;
        cptr [4] = temp >> 24 ;

        temp = val >> 32 ;
        cptr [3] = temp ;
        cptr [2] = temp >> 8 ;
        cptr [1] = temp >> 16 ;
        cptr [0] = temp >> 24 ;
        }
    else if (BYTE_ORDER == BIG_ENDIAN)
    { temp = val ;
        cptr [0] = temp ;
        cptr [1] = temp >> 8 ;
        cptr [2] = temp >> 16 ;
        cptr [3] = temp >> 24 ;

        temp = val >> 32 ;
        cptr [4] = temp ;
        cptr [5] = temp >> 8 ;
        cptr [6] = temp >> 16 ;
        cptr [7] = temp >> 24 ;
        }

    return newval ;
}

int main (void)
{ u_int64_t test ;

    test = 0x1122334455667788LL ;

    printf ("%016llx\n", test) ;
    
    test = endswap_u_int64 (test) ;

    printf ("%016llx\n", test) ;

    return 0 ;
} /* main */

-------------------------------------------------------------------------

There's two code paths; one for big endian and one for little
endian systems. Because the endian-ness of the system is known at
compile time, the if statements and one of the blocks will be
optimised out.

Erik

-- 
+-----------------------------------------------------------+
  Erik de Castro Lopo  nospam_AT_mega-nerd.com (Yes it's valid)
+-----------------------------------------------------------+
"Reality is just a crutch for people that can't handle CyberSpace!!"
- Hank Duderstadt


New Message Reply About this list Date view Thread view Subject view Author view Other groups

This archive was generated by hypermail 2b28 : Thu May 09 2002 - 14:01:22 EEST