Bitwise Operators & Command-Line Arguments
int a = 12; // binary: 1100
int b = 10; // binary: 1010
printf("%d\n", a & b); // 8 (1000) - AND: 1 only where BOTH bits are 1
printf("%d\n", a | b); // 14 (1110) - OR: 1 where EITHER bit is 1
printf("%d\n", a ^ b); // 6 (0110) - XOR: 1 where the bits DIFFER
printf("%d\n", ~a); // -13 - NOT: flips every bit
printf("%d\n", a << 1); // 24 (11000) - shifts bits left, doubles the value
printf("%d\n", a >> 1); // 6 (0110) - shifts bits right, halves the value
Bitwise operators are heavily used in embedded systems and low-level programming for tasks like reading and setting individual hardware flags, compact permission systems (where each bit represents one on/off setting), and fast arithmetic tricks — for example, x << 1 is a very fast way to multiply an integer by 2.
#define READ_PERMISSION 1 // 001
#define WRITE_PERMISSION 2 // 010
#define EXEC_PERMISSION 4 // 100
int permissions = READ_PERMISSION | WRITE_PERMISSION; // combine flags: 011
if (permissions & WRITE_PERMISSION) {
printf("Write access granted\n");
}
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
argc (argument count) tells you how many values were passed when the program was launched from the terminal, and argv (argument vector) is an array of those values as strings. argv[0] is always the program's own name; real arguments start at argv[1].
If compiled to a program called calc, running ./calc 5 10 from a terminal sets argc to 3 and argv to {"./calc", "5", "10"}. You'd then convert argv[1] and argv[2] from strings to numbers using atoi() before doing any arithmetic with them.
& (bitwise AND) and && (logical AND) look similar but do completely different things — the single-ampersand version compares individual bits and can produce surprising numeric results, while the double-ampersand version evaluates two boolean conditions and always produces 0 or 1. Mixing them up in a condition is a subtle, hard-to-spot bug.
Write a program that uses bitwise AND to check whether a number is even or odd, and separately demonstrates left-shifting a number to double it.
#include <stdio.h>
int main() {
int num = 7;
if (num & 1) {
printf("%d is odd\n", num);
} else {
printf("%d is even\n", num);
}
printf("Doubled using shift: %d\n", num << 1);
return 0;
}