How do I do bitwise AND of two numbers?

16,777

Solution 1

`int number = 124 & 100`

Explanation:

Convert 124 to bitwise format, assuming a 32 bit integer. =

`0000 0000 0000 0000 0000 0000 0111 1100`

Convert 100 to bitwise format, assuming a 32 bit integer. =

`0000 0000 0000 0000 0000 0000 0110 0100`

ANDING bitwise:

``````0000 0000 0000 0000 0000 0000 0111 1100
0000 0000 0000 0000 0000 0000 0110 0100
----------------------------------------
0000 0000 0000 0000 0000 0000 0110 0100
---------------------------------------
``````

Which is `100` in decimal! This will be contained in `number` in the above code!

The AND gate truth table is:

``````+-------+---------+
| A | B | A AND B |
+-------+---------+
|0  | 0 |    0    |
|0  | 1 |    0    |
|1  | 0 |    0    |
|1  | 1 |    1    |
+-------+---------+
``````

``````#include <stdio.h>

#define IS_SET(a,b) ((((a & (1 << b)) >> b) > 0?1:0))
#define SET(a,b) ((a |= (1 << b)))
#define CLEAR(a,b) ((a &= ~(1 << b)))

int AND(int a, int b)
{
int i;
int c = 0;
for(i = 0; i < sizeof(int); i++){
if(IS_SET(a,i) && IS_SET(b,i)){
SET(c,i);
}else{
CLEAR(c,i);
}
}
return c;
}

int main(int argc,char *Argv[])
{
int a = 10;
int b = 30;
//Basic UNIT test!
if((a & b) == AND(a,b)){
printf("Test pass!");
}else{
printf("Test fail!");
}
}
``````

Solution 2

Use the bitwise and operator in C `&` like `124 & 100`

Share:
16,777
Author by

vlovystack

Updated on November 23, 2022