FYBCom(CA) C practical Slip 4 Q 1.A

Perform All Bitwise Operations on Two Integers in C

1. Introduction

Bitwise operations are essential in C programming, allowing manipulation of data at the binary level. Understanding them helps in tasks like optimization, encryption, and low-level programming.

2. Problem Statement

Question: Write a C program to accept two integers and perform all bitwise operations.

3. Logic

To perform all bitwise operations on two integers:

  1. Accept two integers from the user.
  2. Use bitwise operators:
    • & (AND)
    • | (OR)
    • ^ (XOR)
    • ~ (NOT)
    • << (Left shift)
    • >> (Right shift)
  3. Display the results of each operation to the user.

4. Source Code

Here’s a beginner-friendly C program:

#include <stdio.h>

int main() {
    int a, b;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    printf("Bitwise AND (a & b) = %d\n", a & b);
    printf("Bitwise OR  (a | b) = %d\n", a | b);
    printf("Bitwise XOR (a ^ b) = %d\n", a ^ b);
    printf("Bitwise NOT (~a) = %d\n", ~a);
    printf("Bitwise NOT (~b) = %d\n", ~b);
    printf("Left shift (a << 1) = %d\n", a << 1);
    printf("Right shift (a >> 1) = %d\n", a >> 1);
    printf("Left shift (b << 1) = %d\n", b << 1);
    printf("Right shift (b >> 1) = %d\n", b >> 1);

    return 0;
}

5. Sample Output

Enter two integers: 5 3
Bitwise AND (a & b) = 1
Bitwise OR  (a | b) = 7
Bitwise XOR (a ^ b) = 6
Bitwise NOT (~a) = -6
Bitwise NOT (~b) = -4
Left shift (a << 1) = 10
Right shift (a >> 1) = 2
Left shift (b << 1) = 6
Right shift (b >> 1) = 1

6. Viva Questions

  1. Q: What are bitwise operators in C?
    A: Operators that work directly on the binary representation of integers.
  2. Q: What does & operator do?
    A: Performs AND operation on each bit of two numbers.
  3. Q: What is the effect of left shift (<<) operator?
    A: Shifts bits to the left, multiplying the number by 2 for each shift.
  4. Q: How does ~ operator work?
    A: Performs bitwise NOT, flipping all bits of the number.
  5. Q: Can bitwise operations be performed on negative numbers?
    A: Yes, they work using two’s complement representation.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top