Added to bitwise operators program

Added a setBit function that prompts the user for which bit to set to true or false, and an insertBitPattern function that adds a set of bits input by the user then inserts them into a specified position.

setBit:

int setBit(int val, int n, bool setToOne)
{
   int mask = setToOne ? 1 << (n-1) : ~(1 << (n-1));

   printf("\nMask created for %s", (setToOne) ? "true:  " : "false: ");
   bitrep(mask);
   printf("\n");

   mask = setToOne ? 1 << (n-1) : ~(1 << (n-1));

   if(setToOne)
   {
       printf("using | (OR)\n");
       val = val | mask;
   }
   else
   {
      printf("using & (AND)\n");
      val = val & mask;      
   }
   
   printf("After set, \n");   
   printf("Bit Representation is:  ");

   return val;
}

insertBitPattern:

void insertBitPattern(int val)
{    
    // forloop variables.
    int i;
    int j = 0;
    // nth bit, mask and user's bit pattern variables.
    int nth_bit;
    int mask;
    char bit[MAXHEX];
    
    printf("Enter bit pattern (set of 0's & 1's): ");
    scanf("%s", &bit);

    //printf("%s length is %d\n", bit, strlen(bit));

    printf("Enter nth position to enter bit pattern: ");
    scanf("%d", &nth_bit);

    // getmask for integer
    mask = 1 <= 0; i--, mask = mask << 1)
    {
        //printf("mask representation:    ");
        if (bit[i] == '1')
        {
            val = val | mask;
            //bitrep(mask);
        }
        else 
        {
            val = val & ~mask;
            //bitrep(~mask);
        }
       /*printf("\n");        
       printf("val representation is:  ");
       bitrep(val);
       printf("\n");*/
    }
    printf("val representation is:  ");
    bitrep(val);
    printf("\n");   
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s