How to use bitwise OR in C

2 Answers

0 votes
#include <stdio.h>

/*

X Y | X | Y
0 0 |   0
0 1 |   1
1 0 |   1
1 1 |   1

*/

void print_bits(int n, int size) {
    for (int i = 1 << (size - 1); i > 0; i = i / 2)
        (n & i) ? printf("1") : printf("0");
}

int main(void) {

    int x = 5, y = 5;
    print_bits(x, 8);
    printf("\n|\n");
    print_bits(y, 8);
    printf("\n=\n");
    print_bits(x | y, 8);
    printf("\n\n\n");

    x = 7, y = 0;
    print_bits(x, 8);
    printf("\n|\n");
    print_bits(y, 8);
    printf("\n=\n");
    print_bits(x | y, 8);
    printf("\n\n\n");
    
    x = 0, y = 6;
    print_bits(x, 8);
    printf("\n|\n");
    print_bits(y, 8);
    printf("\n=\n");
    print_bits(x | y, 8);
    printf("\n\n\n");

    x = 0, y = 0;
    print_bits(x, 8);
    printf("\n|\n");
    print_bits(y, 8);
    printf("\n=\n");
    print_bits(x | y, 8);
    printf("\n\n\n");

    return 0;
}




/*
run:

00000101
|
00000101
=
00000101


00000111
|
00000000
=
00000111


00000000
|
00000110
=
00000110


00000000
|
00000000
=
00000000

*/

 



answered Apr 13, 2023 by avibootz
0 votes
#include <stdio.h>

int main(void) {

    int x = 3, y = 3;
    printf("%d\n", x | y);

    x = 3, y = 0;
    printf("%d\n", x | y);

    x = 0, y = 3;
    printf("%d\n", x | y);

    x = 0, y = 0;
    printf("%d\n", x | y);

    return 0;
}




/*
run:

3
3
3
0

*/

 



answered Apr 13, 2023 by avibootz

Related questions

1 answer 280 views
280 views asked Jun 13, 2015 by avibootz
1 answer 330 views
1 answer 365 views
1 answer 335 views
1 answer 246 views
1 answer 318 views
2 answers 322 views
...