Page 1 of 1

Bit

Posted: Mon Dec 07, 2009 8:58 pm
by Kjell
:idea:

Small library for converting a bit field into a integer and back. Convenient for saving memory when dealing with large amounts of booleans and / or 4D boolean Arrays. Requires a 1D Array called "Bit" to return the values to. Function arguments and results are in big-endian ..

Code: Select all

int bit4(int A, int B, int C, int D)
{
  return A*1+
         B*2+
         C*4+
         D*8;
}

int bit8(int A, int B, int C, int D,
         int E, int F, int G, int H)
{
  return A*  1+
         B*  2+
         C*  4+
         D*  8+
         E* 16+
         F* 32+
         G* 64+
         H*128;
}

int bitX(int B)
{
  int V = 0;
  
  for(--B; B>=0; --B)
  {
    V += Bit[B]*pow(2,B);
  }
  
  return V;
}

void bitField(int X, int B)
{
  for(--B; B>=0; --B)
  {
    int V = pow(2,B);

    if(X >= V)
    {
      Bit[B] = 1;
      X -= V;
    }
    else Bit[B] = 0;
  }
}
And for anything else then 4 or 8-bit, use the bitX function .. or write your own :wink:

K

Posted: Tue Dec 15, 2009 12:19 am
by diki
thanks for these!