Interview

10 Bitwise Interview Questions and Answers

Prepare for technical interviews with this guide on bitwise operations, featuring common questions and answers to enhance your understanding and skills.

Bitwise operations are fundamental to low-level programming and are essential for tasks that require direct manipulation of data at the binary level. These operations are crucial in fields such as embedded systems, cryptography, and performance optimization, where efficient data processing is paramount. Understanding bitwise operations can also provide deeper insights into how computers perform arithmetic and logic operations.

This article offers a curated selection of bitwise operation questions designed to test and enhance your understanding of this critical topic. By working through these questions, you will gain the confidence and knowledge needed to tackle bitwise-related challenges in technical interviews, thereby improving your problem-solving skills and technical acumen.

Bitwise Interview Questions and Answers

1. Write a function to perform bitwise AND, OR, XOR, and NOT operations on two integers.

Bitwise operations are essential in low-level programming for manipulating individual bits of data. These operations include:

  • Bitwise AND (&): Returns a new integer with bits set to 1 where both bits are 1.
  • Bitwise OR (|): Returns a new integer with bits set to 1 where at least one of the bits is 1.
  • Bitwise XOR (^): Returns a new integer with bits set to 1 where the bits are different.
  • Bitwise NOT (~): Inverts all the bits of an integer.

Example:

def bitwise_operations(a, b):
    and_result = a & b
    or_result = a | b
    xor_result = a ^ b
    not_a_result = ~a
    not_b_result = ~b

    return and_result, or_result, xor_result, not_a_result, not_b_result

# Example usage
a = 12  # 1100 in binary
b = 10  # 1010 in binary

results = bitwise_operations(a, b)
print("AND:", results[0])  # 8  (1000 in binary)
print("OR:", results[1])   # 14 (1110 in binary)
print("XOR:", results[2])  # 6  (0110 in binary)
print("NOT a:", results[3]) # -13 (inverts all bits of 12)
print("NOT b:", results[4]) # -11 (inverts all bits of 10)

2. Implement a function to shift bits of an integer left by n positions and right by n positions.

Bitwise shifting involves moving the bits of a binary number to the left or right. In Python, this is done using the << (left shift) and >> (right shift) operators. Shifting bits to the left by n positions multiplies the number by 2^n, while shifting bits to the right by n positions divides the number by 2^n and discards the remainder.

def shift_bits(num, n):
    left_shift = num << n
    right_shift = num >> n
    return left_shift, right_shift

# Example usage:
left, right = shift_bits(8, 2)
print(f"Left Shift: {left}, Right Shift: {right}")
# Output: Left Shift: 32, Right Shift: 2

3. Create a function to generate a bit mask for isolating the k-th bit of an integer.

To generate a bit mask for isolating the k-th bit of an integer, use the left shift operator. By shifting the number 1 to the left by k positions, you create a bit mask where only the k-th bit is set to 1.

def generate_bit_mask(k):
    return 1 << k

# Example usage:
k = 3
mask = generate_bit_mask(k)
print(bin(mask))  # Output: 0b1000

4. Write a function to count the number of set bits (1s) in an integer.

To count the number of set bits (1s) in an integer, use bitwise operations. Repeatedly check the least significant bit (LSB) and shift the integer to the right until all bits have been checked.

def count_set_bits(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

# Example usage
print(count_set_bits(9))  # Output: 2 (binary representation of 9 is 1001)
print(count_set_bits(15)) # Output: 4 (binary representation of 15 is 1111)

5. Implement a function to swap two integers using XOR without using a temporary variable.

To swap two integers using XOR without a temporary variable, leverage the properties of the XOR operation. XORing a number with itself results in 0, and XORing a number with 0 results in the number itself.

def swap(a, b):
    a = a ^ b
    b = a ^ b
    a = a ^ b
    return a, b

# Example usage
x, y = 5, 10
x, y = swap(x, y)
print(x, y)  # Output: 10 5

6. Write a function to check if an integer is even or odd using bitwise operations.

To check if an integer is even or odd using bitwise operations, use the bitwise AND operator (&). The least significant bit (LSB) determines its parity: if the LSB is 0, the number is even; if the LSB is 1, the number is odd.

def is_even(n):
    return (n & 1) == 0

# Test cases
print(is_even(4))  # True, 4 is even
print(is_even(7))  # False, 7 is odd

7. Implement a function to check if an integer is a power of two using bitwise operations.

To check if an integer is a power of two using bitwise operations, use the property that a power of two has exactly one bit set in its binary representation. Subtracting 1 from a power of two results in all bits after the single set bit becoming 1. Perform a bitwise AND operation between the number and the number minus one. If the result is zero, the number is a power of two.

def is_power_of_two(n):
    return n > 0 and (n & (n - 1)) == 0

# Examples
print(is_power_of_two(4))  # True
print(is_power_of_two(5))  # False

8. Given an array of integers where every element appears twice except for one, write a function to find the single unique element using bitwise operations.

To find the single unique element in an array where every other element appears twice, use the XOR operation. XORing all the elements in the array will cancel out the numbers that appear twice, leaving only the unique element.

def find_unique_element(arr):
    unique_element = 0
    for num in arr:
        unique_element ^= num
    return unique_element

# Example usage:
arr = [4, 1, 2, 1, 2]
print(find_unique_element(arr))  # Output: 4

9. Write a function to convert a binary number to its Gray code equivalent and vice versa.

Gray code is a binary numeral system where two successive values differ in only one bit. This property is useful in error correction and minimizing errors in analog to digital conversions.

To convert a binary number to its Gray code equivalent:

  • The most significant bit (MSB) of the Gray code is the same as the MSB of the binary code.
  • Each subsequent bit of the Gray code is obtained by XORing the current bit with the previous bit of the binary code.

To convert a Gray code back to its binary equivalent:

  • The most significant bit (MSB) of the binary code is the same as the MSB of the Gray code.
  • Each subsequent bit of the binary code is obtained by XORing the previous bit of the binary code with the current bit of the Gray code.

Example:

def binary_to_gray(n):
    return n ^ (n >> 1)

def gray_to_binary(n):
    mask = n
    while mask != 0:
        mask >>= 1
        n ^= mask
    return n

# Example usage:
binary_num = 10  # Binary: 1010
gray_code = binary_to_gray(binary_num)
print(f"Gray code of {binary_num} is {gray_code}")

gray_num = 15  # Gray code: 1111
binary_code = gray_to_binary(gray_num)
print(f"Binary code of {gray_num} is {binary_code}")

10. Given an array of n-1 integers in the range from 1 to n, write a function to find the missing number using bitwise operations.

To find the missing number in an array of n-1 integers in the range from 1 to n using bitwise operations, leverage the XOR operation. XORing all the numbers in the array with all the numbers from 1 to n will cancel out the duplicate numbers, leaving only the missing number.

def find_missing_number(arr, n):
    xor_all = 0
    xor_arr = 0
    
    for i in range(1, n + 1):
        xor_all ^= i
    
    for num in arr:
        xor_arr ^= num
    
    return xor_all ^ xor_arr

# Example usage
arr = [1, 2, 4, 5, 6]
n = 6
print(find_missing_number(arr, n))  # Output: 3
Previous

15 Qlik Interview Questions and Answers

Back to Interview
Next

15 Java 11 Interview Questions and Answers