How to use bitwise OR "|" in C

1 Answer

0 votes
#include <stdio.h>

char *toBinFormat(int n);

int main(int argc, char **argv) 
{ 
    // bit level OR (|)(pipe). 
    // result is 1 if one bits is 1 and other bit is zero. 
    // result is 1 when both bits are 0.
    
    char tmp;
    
    tmp = 7 | 1; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 1, toBinFormat(1));
    printf("tmp = 7 | 1 = %3d = %s\n\n", tmp, toBinFormat(tmp));
    
    tmp = 7 | 3;
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 3, toBinFormat(3));
    printf("tmp = 7 | 3 = %3d = %s\n\n", tmp, toBinFormat(tmp));
    
    tmp = 7 | 7; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("tmp = 7 | 7 = %3d = %s\n\n", tmp, toBinFormat(tmp));
   
    tmp = 7 | 32; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 32, toBinFormat(32));
    printf("tmp = 7 | 32 = %3d = %s\n\n", tmp, toBinFormat(tmp));
    
    tmp = 7 | 8; 
    printf("%3d = %s\n", 7, toBinFormat(7));
    printf("%3d = %s\n", 8, toBinFormat(8));
    printf("tmp = 7 | 8 = %3d = %s\n\n", tmp, toBinFormat(tmp));
   
    return(0);
}

char *toBinFormat(int n)
{
    static char binary_value[9]; // without static binary_value is a local 
                                 // array that disappear after return
    int i;
    
    for(i = 0; i < 8; i++)
    {
        binary_value[i] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
    binary_value[i] = '\0';

    return binary_value;
}

/*
run:

  7 = 00000111
  1 = 00000001
tmp = 7 | 1 =   7 = 00000111

  7 = 00000111
  3 = 00000011
tmp = 7 | 3 =   7 = 00000111

  7 = 00000111
  7 = 00000111
tmp = 7 | 7 =   7 = 00000111

  7 = 00000111
 32 = 00100000
tmp = 7 | 32 =  39 = 00100111

  7 = 00000111
  8 = 00001000
tmp = 7 | 8 =  15 = 00001111

*/

 



answered Jun 13, 2015 by avibootz
edited Jun 13, 2015 by avibootz

Related questions

2 answers 134 views
134 views asked Apr 13, 2023 by avibootz
1 answer 206 views
1 answer 254 views
1 answer 226 views
1 answer 153 views
1 answer 208 views
2 answers 199 views
...