Monday, January 1, 2024

Bitwise Brilliance: Bitwise operations and Common interview Questions

Unleashing the Power of Bits: A Dive into Bitwise Operations in C



In the realm of programming, every bit matters. Bitwise operations, often regarded as the unsung heroes of low-level manipulation, allow programmers to perform intricate tasks at the fundamental level of binary representation. This blog embarks on a journey into the world of bitwise brilliance, focusing on the art of bit manipulation in the C programming language.

Bits and Bytes: The Currency of Computers

At the core of every data manipulation lies a binary dance of 0s and 1s. Understanding how to sway these bits with precision opens doors to elegant solutions and efficient algorithms. Bitwise operations provide the tools to navigate this binary landscape, allowing programmers to perform tasks that might seem magical to the uninitiated.

Reversing Binary Integers: A Practical Exploration

Our journey commences with a practical example — the reversal of a binary integer. Through the magic of bitwise XOR, AND, and left-shifting, we'll unravel the steps to flip the binary representation of a number. The intricacies of these operations might seem cryptic at first, but as we dissect each bitwise maneuver, you'll discover the elegance and efficiency they bring to the table.

The Bitwise Toolbox: Shifting Perspectives

Bitwise operations extend far beyond reversing binaries. They are the tools behind setting and clearing specific bits, checking for parity, and even performing arithmetic operations at the level of individual bits. As we delve deeper into this bitwise toolbox, you'll find yourself equipped with the knowledge to tackle a myriad of programming challenges with finesse.

Why Care About Bits?

In a world dominated by high-level abstractions, one might wonder why we should care about bits and bitwise operations. The answer lies in efficiency, optimization, and the sheer joy of mastering the fundamental building blocks of computation. Whether you're working on embedded systems, algorithm design, or simply honing your programming prowess, a solid understanding of bitwise operations will undoubtedly set you apart.

Join us on this journey into the heart of binary manipulation. Bitwise brilliance awaits as we uncover the secrets of C's bitwise operations and witness the transformation of 0s and 1s into a symphony of efficient and elegant code. Let's unravel the magic together!


Write a program to Reverse a Bit integer


#include <stdio.h>
// Function to reverse the bits of an integer
unsigned int reverseBinary(unsigned int num) {
    unsigned int numOfBits = sizeof(num) * 8; // Get the number of bits in an integer
    unsigned int reverseNum = 0;
    for (int i = 0; i < numOfBits; i++) {
        if ((num & (1 << i)) != 0) {
            reverseNum |= 1 << ((numOfBits - 1) - i);
        }
    }
    return reverseNum;
}
int main() {
    unsigned int num;
    // Input binary number
    printf("Enter a binary number: ");
    scanf("%u", &num);
    // Reverse the binary number
    unsigned int reversedNum = reverseBinary(num);
    // Display the result
    printf("Original binary: %u\n", num);
    printf("Reversed binary: %u\n", reversedNum);
    return 0;
}


There are 2 numbers A and B, How many bits you need to flip to equate both the numbers?

#include <stdio.h>
// Function to count the number of bits to be flipped
int countBitsToFlip(int a, int b) {
    int xorResult = a ^ b; // XOR of the two numbers
    int count = 0;
    // Count the set bits in the XOR result
    while (xorResult) {
        count += xorResult & 1;
        xorResult >>= 1;
    }
    return count;
}
int main() {
    int numA, numB;
    // Input numbers
    printf("Enter number A: ");
    scanf("%d", &numA);
    printf("Enter number B: ");
    scanf("%d", &numB);
    // Calculate and display the result
    int flips = countBitsToFlip(numA, numB);
    printf("To make %d and %d equal, you need to flip %d bits.\n", numA, numB, flips);
    return 0;
}

swap the LSB bit to MSB bit of 32 bit integer

#include <stdio.h>

// Function to swap LSB with MSB
unsigned int swapLSBwithMSB(unsigned int num) {
    // Extract LSB and MSB
    unsigned int lsb = num & 1;
    unsigned int msb = (num >> 31) & 1;

    // Clear LSB and MSB in the original number
    num &= 0xFFFFFFFE; // Clear LSB
    num &= 0x7FFFFFFF; // Clear MSB

    // Swap and set the new LSB and MSB
    num |= (lsb << 31); // Set new MSB
    num |= (msb);       // Set new LSB

    return num;
}

int main() {
    unsigned int num;

    // Input number
    printf("Enter a 32-bit number: ");
    scanf("%u", &num);

    // Swap LSB with MSB and display the result
    unsigned int result = swapLSBwithMSB(num);
    printf("Original number: %u\n", num);
    printf("Number after swapping LSB with MSB: %u\n", result);

    return 0;
}

write a program to find endiness?

#include <stdio.h>

// Function to check endianness
int isLittleEndian() {
    int num = 1;
    // Casting the address of the integer to a char pointer
    // allows us to check the value of the first byte (LSB).
    return (*(char*)&num == 1);
}

int main() {
    if (isLittleEndian()) {
        printf("The system is Little Endian.\n");
    } else {
        printf("The system is Big Endian.\n");
    }

    return 0;
}


No comments:

Post a Comment

ESP32-C3 Exploring Embedded Security with ESP32 inbuilt modules

Random Number Generator: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html Random Numbers are ver...