Bitwise Operators in C

This article is the continuation of the Series on the C programming tutorial and carries the discussion on C language programming and its implementation. It aims to provide easy and practical examples for understanding C programming.

In our last tutorial, we discussed the Operators in C programming. In that, we left only bitwise operators. So in this article, we are going to discuss Bitwise operators in C programming.

This is an important topic for interviews in the embedded domain. We can also call this a Bit Manipulation in C.

You can take up any exams at https://www.examlabs.com.

Bitwise Operators in C Programming

Bitwise operators in C serve to manipulate the binary digits of integer values at a fundamental level. These operators enable precise control over the binary structure of integers, finding common applications in low-level programming tasks, hardware interaction, and optimization of specific algorithms.

OperatorsMeaning of operators
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise complement
<<Shift left
>>Shift right

Bitwise AND Operator (&)

The output of bitwise AND is 1 if the corresponding bits of both operands are 1. If either bit of an operand is 0, the result of the corresponding bit is evaluated as 0.

Let us consider the example, the bitwise AND operation of two integers 36 and 13.

36 = 00100100 (In Binary)
13 = 00001101  (In Binary)

Bit Operation of 36 and 13

00100100
00001101                          (&)
________________
00000100 = 4 (In decimal)

Bitwise OR Operator (|)

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, the bitwise OR operator is denoted by |.

Let us consider the example, the bitwise OR operation of two integers 36 and 13.

36 = 00100100 (In Binary)
13 = 00001101  (In Binary)

Bit Operation of 36 and 13

00100100
00001101                          (|)
________________
00101101 = 45 (In decimal)

Bitwise XOR (exclusive OR) Operator (^)

The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^.

36 = 00100100 (In Binary)
13 = 00001101  (In Binary)

Bit Operation of 36 and 13

00100100
00001101                          (^)
________________
00101001 = 41 (In decimal)

Bitwise Complement Operator (~)

Bitwise complement operator is a unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.

Right Shift Operator

The Right shift operator shifts all bits towards the right by a certain number of specified bits. It is denoted by >>.

212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)

Left Shift Operator

The Left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by <<.

212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 =11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)

That is all about the Bitwise operator. Now, we will see the common questions asked in the interview.

You can also read embedded interview topics, number complement programs in C, Pointers in C, and Stringizing and token pasting operators in C.

Bitwise Operators in C – Interview Questions

1. How to set a particular bit in a variable or register?

To set any bit in a variable, use the OR operator.

Variable = Variable | (1<<x)   (or)   Variable |= (1<<x)

Here, ‘x‘ indicates the position of the bit

Example: Set the 4th bit in given register A.

A = A | (1<<4)  (or)  A |= (1<<4) 

2. How to clear a particular bit in a number?

To clear any bit in a variable, Use (AND ) and (NEG (~)) operators.

Variable = Variable & ~(1<<x)    (or)    Variable &= ~(1<<x)

x‘ indicates the position of the bit

Example: Clear the 5th bit in given register B.

B = B & ~(1<<5)     (or)      B &= ~(1<<5) 

3. How to toggle or flip a particular bit in a number?

To toggle any bit in a variable, Use (^) exclusive OR operator.

Variable = Variable ^ (1<<x)    (or)     Variable ^= (1<<x)   

x‘ indicates the position of the bit

Example: Toggle the 2nd bit in given register B.

B = B ^ (1<<2)       (or)        B ^= (1<<2)

4. Toggle a given range of bits

For example, take the number 245. The equivalent binary format is 1111101 and the range is 4 to 7. So, the output should be 00000101 which is 5 in decimal.

unsigned int rangeToggle(unsigned int num, unsigned int i , unsigned int j)
{
  return num ^ ((1<<(j-i)+1)-1)<<i;
}

5. How to check particular bit is set or not in a number?

To check any bit in a variable, Use (&) And Operator.

Variable & (1<<x)

x‘ indicates the position of the bit

Example: Check whether the 3rd bit is set or not.

if((variable & (1<<3)) == 0) 
{
    printf("bit is not set");
} 
else 
{
    printf("bit is set");
}

6. How to represent the above all things in MACRO for Real-time code?

#define SET_BIT(Variable, bit_position)    Variable |= (1<< bit_position) 
#define CLEAR_BIT(Variable, bit_position)    Variable &= ~(1<< bit_position) 
#define TOGGLE_BIT(Variable, bit_position)    Variable ^= (1<< bit_position) 
#define CHECK_BIT_IS_SET_OR_NOT(Variable, bit_position)    Variable & (1<< bit_position)

7. Write MACRO to Swap the bytes in 16bit Integer Variable.

#define ByteSwap16(Value) ((Value & 0x00FF) << 8) | ((Value & 0xFF00) >> 8)

8. Write MACRO to Swap the bytes in a 32-bit Integer Variable.

#define ByteSwap32(Value) ((Value & 0x000000FF) << 24) |
                                  ((Value & 0x0000FF00U) <<  8) |
                                  ((Value & 0x00FF0000U) >>  8) |
                                  ((Value & 0xFF000000U) >> 24)

9. Write MACRO to Swap the bytes in a 64-bit Integer Variable.

#define ByteSwap64(Value)   ((Value & 0x00000000000000FFU) << 56) | 
                                ((Value & 0x000000000000FF00U) << 40) | 
                                ((Value & 0x0000000000FF0000U) << 24) | 
                                ((Value & 0x00000000FF000000U) <<  8) | 
                                ((Value & 0x000000FF00000000U) >>  8) | 
                                ((Value & 0x0000FF0000000000U) >> 24) | 
                                ((Value & 0x00FF000000000000U) >> 40) | 
                                ((Value & 0xFF00000000000000U) >> 56)

10. Find whether the number is odd or even

void odd_even( uint8_t  number )
{
  if( number & 1 )
  {
    printf(" Number is Odd\r\n");
  }
  else
  {
    printf(" Number is Even\r\n");
  }
}

11. Clear the last right side set a bit of a number

For example, take the number 144. The equivalent binary format is 10010000. So, the output should be 10000000 which is 128 in decimal.

uint8_t remove_last_set_bit( uint8_t  number )
{
    return (n & (n - 1));
}

12. Check if the number is a power of 2

void powerOf2( uint8_t  number ) 
{
  if(n & (n - 1))
  {
    printf("Number is not power Of 2");
  }
  else
  {
    printf("Number is power Of 2");
  }
}

13. Count the number of set bits in a number

unsigned int countSetBits( unsigned int number ) 
{
  unsigned int count = 0;
  while( number != 0)
  {
    count++;
    number &= (number-1);
  }

  return count;
}

14. Swap two bits at a given position in an integer

unsigned int swapBits( unsigned int number, unsigned int i, unsigned int j ) 
{
  number ^= (1 << i);
  number ^= (1 << j);
  
  return number;
}

15. Swap all even and odd bits

For example, take the number 154. The equivalent binary format is 10011010. So, the output should be 01100101 which is 101 in decimal.

unsigned int swapOddEvenBits( unsigned int number ) 
{
  return ( ( number & 0xAAAAAAAA ) >> 1 ) | ( ( number & 0x55555555 ) << 1 );
}

In our next article, we will discuss datatypes in C programming.

You can also read the below tutorials.

Linux Device Driver TutorialsC Programming Tutorials
FreeRTOS TutorialsNuttX RTOS Tutorials
RTX RTOS TutorialsInterrupts Basics
I2C Protocol – Part 1 (Basics)I2C Protocol – Part 2 (Advanced Topics)
STM32 TutorialsLPC2148 (ARM7) Tutorials
PIC16F877A Tutorials8051 Tutorials
Unit Testing in C TutorialsESP32-IDF Tutorials
Raspberry Pi TutorialsEmbedded Interview Topics
Reset Sequence in ARM Cortex-M4BLE Basics
VIC and NVIC in ARMSPI – Serial Peripheral Interface Protocol
STM32F7 Bootloader TutorialsRaspberry PI Pico Tutorials
STM32F103 Bootloader TutorialsRT-Thread RTOS Tutorials
Zephyr RTOS Tutorials – STM32Zephyr RTOS Tutorials – ESP32
AUTOSAR TutorialsUDS Protocol Tutorials
Product ReviewsSTM32 MikroC Bootloader Tutorial
VHDL Tutorials
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Table of Contents