xxxxxxxxxx
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)
Note: Overflow is ignored while computing 2's complement.
xxxxxxxxxx
Bitwise operations takes in 1-2 integer(s) and returns the result of
taking an operation on every binary digit (except shifts).
Bitwise and (&)
-14 & 23
= 0b110010 &
0b010111
= 0b010010
= 18
Bitwise or (|)
-14 | 23
= 0b110010 |
0b010111
= 0b110111
= -9
Bitwise not (~)
~23
= ~0b010111
= 0b101000
= -24
Bitwise xor (^)
-14 ^ 23
= 0b110010 ^
0b010111
= 0b100101
= -27
Left shift (<<)
-14 << 2
= 0b 110010 << 2
= 0b11001000
= -56
The bits on the right is filled with 0s.
Arithmetic right shift (>>, >>> in some languages)
-14 >> 2
= 0b110010 >> 2
= 0b111100
= -4
23 >> 2
= 0b010111 >> 2
= 0b000101
= 5
The fractional part is ignored and the bits on the left are filled
with 0s or 1s, depending on the sign of the input.
Logical right shift (>>> in some languages)
-14 >>> 2
= 0b110010 >>> 2
= 0b001100
= 12
23 >>> 2
= 0b010111 >>> 2
= 0b000101
= 5
The fractional part is ignored and the bits on the left are filled with 0s.
xxxxxxxxxx
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4
xxxxxxxxxx
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
xxxxxxxxxx
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)
xxxxxxxxxx
#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
xxxxxxxxxx
bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)
xxxxxxxxxx
// C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;
// The result is 00000001
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);
// The result is 00001101
printf("a|b = %d\n", a | b);
// The result is 00001100
printf("a^b = %d\n", a ^ b);
// The result is 11111010
printf("~a = %d\n", a = ~a);
// The result is 00010010
printf("b<<1 = %d\n", b << 1);
// The result is 00000100
printf("b>>1 = %d\n", b >> 1);
return 0;
}
xxxxxxxxxx
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
xxxxxxxxxx
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)