C - Using the bitwise | operator

Introduction

The | is the bitwise OR operator, also known as the inclusive OR.

The & is the bitwise AND operator.

The following code demonstrates how to use the bitwise OR operator to set bits in a byte.

The OR value is defined as the constant SET at Line 2. It's binary 00100000.

Demo

#include <stdio.h> 
#define SET 32 // w w  w.ja va2s  .  c  o m

char *to_binary(int n); 

int main() 
{ 
   int bor,result; 

   printf("Type a value from 0 to 255: "); 
   scanf("%d",&bor); 
   result = bor | SET; 

   printf("\t%s\t%d\n",to_binary(bor),bor); 
   printf("|\t%s\t%d\n",to_binary(SET),SET); 
   printf("=\t%s\t%d\n",to_binary(result),result); 
   return(0); 
} 

char *to_binary(int n) 
{ 
   static char bin[9]; 
   int x; 

   for(x=0;x<8;x++) 
   { 
       bin[x] = n & 0x80 ? '1' : '0'; 
       n <<= 1; 
   } 
   bin[x] = '\0'; 
   return(bin); 
}

Result

Related Topic