Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been assigned to create a function which works as the bitwise complement operator. So far what I have created is this:

#include <stdio.h>

/**
    print the binary equivalent of a signed integer value.

*/

void printBinary(int n){
    int i;
    unsigned k = 1 << 31;
    for(i = 0; i < sizeof(int) * 8; ++i){
        if ((n & (k >> i)) == (k >> i))
            printf("1");
        else
            printf("0");

        if ( (i+1) % 8 == 0)
            printf(" ");
    }
    putchar('\n');
}


/**
 The function flip receives a signed integer n and inverts every bit of n and
 returns the inverted integer. That is, it performs equivalent to bitwise complement
 operator ~.
 You must not use ~ for doing the function.
 You must not change the prototype of function flip.
 You must not change anywhere else of the program apart from developing function flip.

*/

int flip(int n){
    // Your code starts here
	
	int i;
	unsigned int a = 1 << 31;
	
	printBinary(n);
	for(i=0; i< sizeof(int) * 8; i++)
	{
		if(n & (a >> i))
			n = n & (0 >> i);
		else 
			n = n | (1 >> i);
	}
	printBinary(n);
	
    return n;
}

int main(){
    // Do not change anything here.
    // There are 3 test cases, you need to pass through all of them.
    // Run the program after completing flip function.

    int k = 5;
    int p = flip(k);
    int count = 0;
    if (p == -6){
        printf("First Test case: Passed\n");
        count++;
    }
    else{
        printf("First Test case: Failed\n");
    }

    p = flip(-1);
    if (p == 0){

        printf("Second Test case: Passed\n");
        count++;
    }
    else{
        printf("Second Test case: Failed\n");
    }

    p = flip(100);
    if (p == -101){
        printf("Third Test case: Passed\n");
        count++;
    }
    else{
        printf("Third Test case: Failed\n");
    }

    // checking if all test cases were passed.
    if (count == 3){
        printf("Well done\n");
    }
    else{
        printf("%d out of 3 test cases are passed\n", count);
        printf("Please recheck your function, you are missing something\n");
    }



    return 0;
}



In the flip function I have tried to do it. The function works correctly for flipping the 1 bits but it isn't flipping the 0 bits. I am not able to get it. I have used the bitwise & and | operator.

What I have tried:

I thought it might be the defect of the if else conditional statement so I tried using if else if ladder but it is not working.
Posted
Updated 20-Sep-18 4:35am
Comments
Richard MacCutchan 19-Sep-18 11:31am    
It is fairly straightforward:

IF bit == 1
bit = 0
ELSE
bit = 1
REPEAT
Zeeking99 19-Sep-18 11:38am    
That's what I am trying to do but I can't manipulate bits individually.
Richard MacCutchan 19-Sep-18 11:59am    
Why not, you already have code in your question that checks for bits being set?
Try this:

unsigned int orig = 0x0F1E3C78;
unsigned int flip = 0;

for (int i = 0; i < 32; ++i)
{
if ((orig & (1 << i)) == 0)
flip = flip + (1 << i);
}
Jochen Arndt 19-Sep-18 12:10pm    
There is no need to clear bits when using a variable initialised to zero as shown by Richard. Then you would have to set bits only.

But there is a much simpler solution: Using XOR.
Zeeking99 20-Sep-18 10:31am    
Yeah I got it. Thanks for help.

I like to write functions that can work generically so that is what I would do. I would write one function to test a bit in a byte, one to set a bit, and one to clear a bit.

The general tactic to test a bit is to shift the value 1 to the specified bit position and then check the result of the binary AND operation between the shifted bit and the byte. To set a bit is very similar - shift a one to the right place and OR it with the byte. Clearing a bit is a little different : shift the bit, complement the shifted value, and then AND it with the byte.

You can do what you need to by using these three functions. If a bit is set then clear it and if it is clear then set it. Now do this for every bit in the byte. You might have noticed that I keep referring to bytes. That is because if you can do this for one byte then you can do it for as many bytes as you want. Just tell it how many bytes you passed or pass them to the function one at a time.
 
Share this answer
 
C
void print_binary( int n )
{
  const int BITS = sizeof(int)*8; // bit count of int variable
  const unsigned MSB = (1 << (sizeof(int)*8-1)); // this is most significant bit
  int i;
  for (i = 0; i < BITS; ++i)
  {
    char c = (n & MSB) ? '1' : '0';
    putchar(c);
    n <<= 1;
  }
  putchar('\n');
}


int flip(int n)
{
  print_binary(n);
  int flipped = (n ^ -1); // the integer representation of -1 has all bits set
  print_binary(flipped);
  return flipped;
}
 
Share this answer
 
Your function fail because this line
C++
n = n & (0 >> i);

is just erasing n.
To clear 1 bit the way you try, you need to use the not operation:
C++
n = n & ( ~ (1 >> i));


But with the xor operation, your code can be simplified to:
C++
for(i=0; i< sizeof(int) * 8; i++)
{
    if(n & (a >> i))
        n = n & (0 >> i);
    else
        n = n | (1 >> i);
    n = n ^ (1 >> i);
}

Bitwise operations can change all bits at same time, the not can further simplify the code to 1 line:
C++
n = ~ n; // flips all bits


Bitwise operations in C - Wikipedia[^]
 
Share this answer
 
v2
There is an another way of doing it by using bitwise or. The function checks for a set bit and leaves it as it is because it is already initialized with zero. If the function finds an unset bit it sets it by using bitwise or.

#include <stdio.h>

/**
    print the binary equivalent of a signed integer value.

*/

void printBinary(int n){
    int i;
    unsigned k = 1 << 31;
    for(i = 0; i < sizeof(int) * 8; ++i){
        if ((n & (k >> i)) == (k >> i))
            printf("1");
        else
            printf("0");

        if ( (i+1) % 8 == 0)
            printf(" ");
    }
    putchar('\n');
}


/**
 The function flip receives a signed integer n and inverts every bit of n and
 returns the inverted integer. That is, it performs equivalent to bitwise complement
 operator ~.
 You must not use ~ for doing the function.
 You must not change the prototype of function flip.
 You must not change anywhere else of the program apart from developing function flip.

*/

int flip(int n)
{
    // Your code starts here
  int index, temp = 0;
  unsigned int k = 1;

  for(index=0;index<sizeof(int)*8;index++)
  {
    if(n&(k<<index))
      continue;
    else
      temp = (temp | (k<<index));
  }
    return temp;
}

int main(){
    // Do not change anything here.
    // There are 3 test cases, you need to pass through all of them.
    // Run the program after completing flip function.

    int k = 5;
    int p = flip(k);
    int count = 0;
    if (p == -6){
        printf("First Test case: Passed\n");
        count++;
    }
    else{
        printf("First Test case: Failed\n");
    }

    p = flip(-1);
    if (p == 0){

        printf("Second Test case: Passed\n");
        count++;
    }
    else{
        printf("Second Test case: Failed\n");
    }

    p = flip(100);
    if (p == -101){
        printf("Third Test case: Passed\n");
        count++;
    }
    else{
        printf("Third Test case: Failed\n");
    }

    // checking if all test cases were passed.
    if (count == 3){
        printf("Well done\n");
    }
    else{
        printf("%d out of 3 test cases are passed\n", count);
        printf("Please recheck your function, you are missing something\n");
    }



    return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900