270 Bitwise Ops
270 Bitwise Ops
Ben Langmead
[email protected]
www.langmead-lab.org
2
Bitwise operators
Binary: 0 0 1 1 0 1 0 1
Place value: 27 26 25 24 23 22 21 20
25 + 24 + 22 + 20 = 32 + 16 + 4 + 1 = 53
3
Bitwise operators
4
Bitwise operators
#include <stdio.h>
int main() {
int a = 12;
int b = 25;
printf("%d & %d = %d\n", a, b, a & b);
return 0;
}
5
Bitwise operators
Since ints are 32-bit (4-byte) values, this is a more accurate picture:
00000000000000000000000000001100 = 12
& 00000000000000000000000000011001 = 25
________________________________
00000000000000000000000000001000 = 8 (In decimal)
6
Bitwise operators
7
Bitwise operators
#include <stdio.h>
int main() {
int a = 12;
int b = 25;
printf("%d | %d = %d\n", a, b, a | b);
return 0;
}
8
Bitwise operators
9
Bitwise operators
#include <stdio.h>
int main() {
int a = 25;
int b = 5;
printf("%d << %d = %d\n", a, b, a << b);
return 0;
}
10
Bitwise operators
11
Bitwise operators
#include <stdio.h>
int main() {
int a = 25;
int b = 4;
printf("%d >> %d = %d\n", a, b, a >> b);
return 0;
}
12
Bitwise operators
#include <stdio.h>
int main() {
int num = 53;
char bin_str[33] = {'\0'};
int tmp = num;
for(int i = 0; i < 32; i++) {
if((tmp & 1) != 0) { // least significant bit set?
bin_str[31-i] = '1'; // prepend 1
} else {
bin_str[31-i] = '0'; // prepend 0
}
tmp >>= 1; // shift right by 1
}
printf("%d in binary: %s\n", num, bin_str);
return 0;
}
13
Bitwise operators
14