/*
 *  endian.c
 *  PSP Development
 *
 *  Created by XArt on 17/03/2007.
 *  Copyright 2007 XArt. All rights reserved.
 *
 */

#include "endian.h"

/*
 Converts a 16-bit integer from big-endian format to the host’s native byte order.
 
 Parameters
 arg
 The integer whose bytes should be swapped.
 
 Return Value
 The integer with its bytes swapped. If the host is big-endian, this function returns arg unchanged.
 */
short int swapInt16BigToHost(short int arg)
{
   short int i=0;
   int checkEndian = 1;  
   if( 1 == *(char *)&checkEndian )
   {
      // Intel (little endian)
      i=arg;
      i=(i>>8)|(i<<8);
   }
   else
   {
      // PPC (big endian)
   }
   return i;
}

/*
 Converts a 16-bit integer from little-endian format to the host’s native byte order.
 
 Parameters
 arg
 The integer whose bytes should be swapped.
 
 Return Value
 The integer with its bytes swapped. If the host is little-endian, this function returns arg unchanged.
 */
short int swapInt16LittleToHost(short int arg)
{
   short int i=0;
   int checkEndian = 1;  
   if( 1 == *(char *)&checkEndian )
   {
      // Intel (little endian)
   }
   else
   {
      // PPC (big endian)
      i=arg;
      i=(i>>8)|(i<<8);
   }
   return i;
}

/*
 Converts a 32-bit integer from big-endian format to the host’s native byte order.
 
 Parameters
 arg
 The integer whose bytes should be swapped.
 
 Return Value
 The integer with its bytes swapped. If the host is big-endian, this function returns arg unchanged.
 */
int swapInt32BigToHost(int arg)
{
   int i=0;
   int checkEndian = 1;  
   if( 1 == *(char *)&checkEndian )
   {
      // Intel (little endian)
      i=arg;
      i=((i&0xFF000000)>>24)|((i&0x00FF0000)>>8)|((i&0x0000FF00)<<8)|((i&0x000000FF)<<24);
   }
   else
   {
      // PPC (big endian)
   }
   return i;
}

/*
 Converts a 32-bit integer from little-endian format to the host’s native byte order.
 
 Parameters
 arg
 The integer whose bytes should be swapped.
 
 Return Value
 The integer with its bytes swapped. If the host is little-endian, this function returns arg unchanged.
 */
int swapInt32LittleToHost(int arg)
{
   int i=0;
   int checkEndian = 1;  
   if( 1 == *(char *)&checkEndian )
   {
      // Intel (little endian)
   }
   else
   {
      // PPC (big endian)
      i=arg;
      i=((i&0xFF000000)>>24)|((i&0x00FF0000)>>8)|((i&0x0000FF00)<<8)|((i&0x000000FF)<<24);
   }
   return i;
}
