/*
   <p>Display the last n bits of an int.</p>

   <kbd>
   <b>environ - C programming support functions</b><br>
   Copyright (C) 2005  Martin C Gregorie
   
   This program is free software; you can redistribute it and/or
   modify it under the terms of the Lesser GNU General Public License.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
  
   You should have received a copy of the Lesser GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
   </kbd>
  
   <p>Contact Martin Gregorie at <i>martin@gregorie.org</i></p>
*/

/*
   Display the last <u>n</u> bits of the integer value <u>v</u>.
   Returns a string containing the value as a list of 0 and 1 characters.
*/
#include <environ.h>
#ifdef LINUX
#include <stdlib.h>
#endif

char *bitsout(int v, int n)
{
   static char *buff = 0;
   int         i;
   int         k;

   if (buff)
      free(buff);

   buff = (char*)malloc(n+1);
   if (!buff)
      error("bitsout", "can't obtain buffer space", "");

   for (i = 0; i < n; i++)
   {
      k = 1 << (n - 1 - i);
      if (v & k)
         buff[i] = '1';
      else
         buff[i] = '0';
   }

   buff[n] = 0;
   return buff;
}


