/*---------------------------------------------------------------*/
/*   Copyright (c) 1992 Regents of the University of California  */
/*                 All Rights Reserved                           */
/*---------------------------------------------------------------*/
/*-----------------------------------------------------------------
  Bit manipulation functions.

  Development History:
    Begun: 03/20/92 - Todd King

  Version:
      %W%     (UCLA/IGPP)    %G%
-----------------------------------------------------------------*/
#include "BC.h"

/*****************************************************************/
/* sub functions                                                 */
/*****************************************************************/
BCBinary 
BCMakeMask (unsigned int location, unsigned int numbits)
{
   unsigned int index;
   BCBinary mask = 1;

   for (index = 2; index <= numbits; index++) {
      mask = mask << 1;
      mask++;
   }
   if(location > 0) mask = (mask << location);

   return(mask);
}

BCBinary 
BCCompliment (BCBinary bitfield, unsigned int numbits)
{
   BCBinary mask;

   mask   = BCMakeMask(0, numbits);

   return(bitfield^mask);
}


BCBinary 
BCExtractBits (BCBinary data, unsigned int location, unsigned int numbits)
{
   BCBinary mask;

   mask      = BCMakeMask(location, numbits);

   return((data & mask) >> location);
}

/*------------------------------------------------------
  Sets bits in a BCBinary value. Only the 'numbits'
  least significant bits of 'value' are transferred to
  'data' at the location specified.
--------------------------------------------------------*/
BCBinary 
BCSetBits (BCBinary data, unsigned int location, unsigned int numbits, BCBinary value)
{
   BCBinary mask;
   BCBinary comp;
   BCBinary mvalue;

   mvalue = value & BCMakeMask(0, numbits);
   mask = BCMakeMask(location, numbits);
   comp	= BCCompliment(mask, sizeof(BCBinary) * 8);

   return((data & comp)  + (mvalue << location));
}
