87.1k views
3 votes
Write a C program that creates a function bitFlip() that takes an int parameter and returns an int that has all of the int that was passed in bits flipped.

It changes all 0s to 1s and all 1s to 0s. In the main function, read in an int num using scanf, call bitFlip(), and the function returns num with its bits flipped.
Output example:
Enter an integer: 2
Integer before bits were flipped: 00000000000000000000000000000010
Integer after bits were flipped: 11111111111111111111111111111101
The flipped number is: -3

User Joey Rohan
by
8.4k points

1 Answer

5 votes

Answer:

Here's an example C program that implements the bitFlip() function:

#include <stdio.h>

int bitFlip(int num) {

return ~num; // Use bitwise NOT operator to flip all bits

}

int main() {

int num;

printf("Enter an integer: ");

scanf("%d", &num);

printf("Integer before bits were flipped: %032d\\", num); // Use %032d to print leading zeros

num = bitFlip(num);

printf("Integer after bits were flipped: %032d\\", num);

printf("The flipped number is: %d\\", num);

return 0;

}

The bitFlip() function takes an int parameter num and returns an int with all of its bits flipped using the bitwise NOT operator ~.

In the main() function, we first read in an integer num using scanf(). We then print out the binary representation of num using the %032d format specifier to ensure that it has 32 bits with leading zeros. We then call bitFlip() to flip the bits of num and print out the binary representation of the flipped number. Finally, we print out the value of the flipped number using %d.

Sample output:

Enter an integer: 2

Integer before bits were flipped: 00000000000000000000000000000010

Integer after bits were flipped: 11111111111111111111111111111101

The flipped number is: -3

Step-by-step explanation:

User TheTypan
by
7.0k points