delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/05/29/19:18:44

Date: Fri, 30 May 1997 11:19:05 -0700
From: Bill Currie <billc AT blackmagic DOT tait DOT co DOT nz>
Subject: big endian class
To: djgpp AT delorie DOT com
Reply-to: billc AT blackmagic DOT tait DOT co DOT nz
Message-id: <338F1A19.474E@blackmagic.tait.co.nz>
Organization: Tait Electronics NZ
MIME-version: 1.0

This is just a little class for easy handling of big endian shorts and
longs (signed and unsigned) that I though some of you might be
interested in.

If anyone can figure a better way of byte swapping longs (without useing
bswap), preferably in c, please let me know as gcc can't optimise
swapBytes(long) or swapBytes(ulong) when called with constants (due to
the assembly code).

usage (eg):

BigEndian<short> value;
value=0x1234;
printf ("%x",(short)value);

Enjoy
Bill
-- 
Leave others their otherness.

------------------------8<----------------------------------

// Written by Bill Currie (billc AT blackmagic DOT tait DOT co DOT nz) 30/5/97
// No strings attached ('cept leave my name in please)

typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned long ulong;

static inline __attribute__((const)) short swapBytes(short val)
{
    ushort v=val;
    return (v>>8)|(v<<8);
}

static inline __attribute__((const)) long swapBytes(long val)
{
    long v;
    asm ("              \n\
        rorw    $8,%w0  \n\
        rorl    $16,%k0 \n\
        rorw    $8,%w0  \n\
    "
    :"=r"(v)
    :"0"(val)
    );
    return v;
}

static inline __attribute__((const)) ushort swapBytes(ushort val)
{
    return ((ushort)(val<<8))|((ushort)(val>>8));
}

static inline __attribute__((const)) ulong swapBytes(ulong val)
{
    ulong v;
    asm ("              \n\
        rorw    $8,%w0  \n\
        rorl    $16,%k0 \n\
        rorw    $8,%w0  \n\
    "
    :"=r"(v)
    :"0"(val)
    );
    return v;
}

template <class T>
class BigEndian {
    T value;
public:
    BigEndian(){}
    BigEndian(T val):value(swapBytes(val)){}
    BigEndian(const BigEndian &be):value(be.value){}
    BigEndian &operator = (const BigEndian &be){value=be.value; return
*this;}
    T operator = (T val){value=swapBytes(val); return val;}
    operator T () const {return swapBytes(value);}
};

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019