HomeAbout UsContact Us

C program showcasing bitwise operations

By embeddedSoft
Published in Embedded C/C++
September 21, 2022
1 min read
C program showcasing bitwise operations

The bitwise operators available in C are,

bitwise AND – ‘&’

bitwise OR – ‘|’

bitwise XOR – ‘^’

left-shift operator – ‘<<’

right-shift operator – ‘>>’

bitwise NOT (1’s complement) – ‘~’

This C program shows some of common usage of the bitwise operators. The bitwise operators are widely used in embedded C programming.

#include <stdio.h>

int main(void)
{
  int x = 0x1u;

  // Set 2nd bit
  x |= (1u << 2);
  printf("%d\n", x);

  // Clear 2nd bit
  x &= ~(1u << 2);
  printf("%d\n", x);

  // Toggle 2nd bit
  x ^= (1 << 2);
  printf("%d\n", x);

  // Test 2nd bit
  x & (1u << 2) ? puts("true") : puts("false");
  
  return 0;
}

Code walk-through

The code fragment x |= (1u << 2); sets the 2nd bit by shifting the value 1 left by 2 positions. Similarly the code fragment x &= ~(1u << 2); clears the second bit by shifting the value 1 by 2 positions to the left and doing a 1’s complement.

The line x ^= (1 << 2); toggles the 2nd bit by left shifting the value 1 by 2 positions and XORing with the value to be modified.

The code fragment  x & (1u << 2) ? puts(“true”) : puts(“false”); tests the bit at position 2 by creating a mask by shifting 1 by 2 positions to the left and use the bit-wise & operator to check if the result is not 0 or otherwise.


Tags

#C#C++#bitwise
Previous Article
Angle between hour and minute hands of analogue clock using C
embeddedSoft

embeddedSoft

Content editor

Related Posts

Example C code to set 5 bits starting from position 10
Example C code to set 5 bits starting from position 10
September 22, 2022
1 min

Quick Links

Advertise with usAbout UsContact Us

Social Media