Improving Code Performance With Bitwise Operation in C
Most every programming language has bitwise operation, and I am curious about the use of bitwise operation, and why the bitwise operation exists in programming languages.
Before learning bitwise operations, we should have a good understanding about some kind of numeral system : binary, hexadecimal, and decima.
Some kind of numeral system:
Binary code : binary code is code used in digital computers, based on a binary number system in which there are only two possible states, off and on, usually symbolized by 0 and 1.
Hexadecimal : hexadecimal (also base-16 or simply hex) numeral system is a positional numeral system that represents numbers using a radix (base) of 16. Unlike the decimal system representing numbers using 10 symbols, hexadecimal uses 16 distinct symbols, most often the symbols “0”–”9" to represent values 0 to 9, and “A”–”F” (or alternatively “a”–”f”) to represent values from 10 to 15.
Decimal : Decimal is a term that describes the base-10 number system, probably the most commonly used number system. The decimal number system consists of ten single-digit numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.
Based on my perception coding on binary will improve application performance, so here are some bitwise operation to improve performance :
- Using binary left shift for multiplication by 2
int main(){
unsigned int a = 10;
a= a * 2;
printf("a : %d \n", a);
unsigned int b = 10;
b= b << 1;
printf("b : %d \n", b);
return 0;
}
PS D:\wahyu\c\array> .\str.exe
a : 20
b : 20
2. Using binary left shift for Devision by 2
int main(){
unsigned int a = 20;
a= a / 2;
printf("a : %d \n", a);
unsigned int b = 20;
b= b >> 1;
printf("b : %d \n", b);
return 0;
}
PS D:\wahyu\c\array> .\str.exe
a : 10
b : 10
3. Check the number is even or odd, use binary AND operation (&) instead using modulus (%)
int main(){
unsigned int a = 20;
a= a % 2;
printf("a : %d \n", a);
unsigned int b = 20;
b= b & 1;
printf("b : %d \n", b);
unsigned int c = 21;
c = c & 1;
printf("c : %d \n", c);
return 0;
}
PS D:\wahyu\c\array> .\str.exe
a : 0
b : 0
c : 1
4. Check the char or int data type is equal or not
int main(){
char a = 'A';
char b = 'A';
// 1 means equal
printf(" a compare b = %d\n", a == b);
// using exclusive OR (XOR), if 0 means equal
printf(" a compare b = %d\n", a^b);
return 0;
}
PS D:\wahyu\c\array> .\str.exe
a compare b = 1
a compare b = 0
Source :
https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm