Bitwise Calculator: Complete Guide to Bitwise Operations
A Bitwise Calculator is an essential tool for embedded systems engineers, software developers, network administrators, and electronics students who work at the binary level. Unlike standard arithmetic, bitwise operations act on the individual binary digits (bits) of integers, making them fundamental to hardware registers, protocol flags, cryptographic algorithms, and compiler-level optimisation.
What are Bitwise Operations?
Bitwise operations treat each operand as a sequence of binary digits and apply a logical function bit-by-bit. The six primary bitwise operations are: AND, OR, XOR, NOT, Left Shift (SHL), and Right Shift (SHR). They are supported natively in all major programming languages including C, C++, Java, Python, and JavaScript, as well as in hardware description languages like VHDL and Verilog.
AND (&) – Bit Masking
AND outputs 1 only when both corresponding bits are 1. Formula: A & B. Primary use: masking — extracting specific bits from a register. For example, 0b11001100 & 0b00001111 = 0b00001100. In C: uint8_t flags = status & 0x0F; to isolate the lower nibble.
OR (|) – Bit Setting
OR outputs 1 when at least one bit is 1. Formula: A | B. Primary use: setting bits without disturbing others. Example: config |= 0x04; sets bit 2 of a configuration register while leaving all other bits unchanged.
XOR (^) – Bit Toggling
XOR outputs 1 only when bits differ. Formula: A ^ B. Primary uses: toggling bits, simple encryption (XOR cipher), checksum generation, and detecting differences. A well-known trick: A ^ A = 0 and A ^ 0 = A.
NOT (~) – Bitwise Complement
NOT inverts all bits of a single operand. Formula: ~A. On a 32-bit system, ~255 = 4294967040 (all 32 bits flipped). NOT is used for creating complement masks, negation in two's complement arithmetic, and inverting control bits.
Left Shift (<<) and Right Shift (>>)
Left shift multiplies by powers of 2: A << n = A × 2ⁿ. Right shift divides: A >> n = A ÷ 2ⁿ (integer). Example: 1 << 8 = 256. Shifts are heavily used in fixed-point arithmetic, PWM duty cycle calculations, and protocol field extraction.
Practical Examples
- Check if bit 3 is set:
value & (1 << 3) - Set bit 5:
value |= (1 << 5) - Clear bit 2:
value &= ~(1 << 2) - Toggle bit 7:
value ^= (1 << 7) - Fast multiply by 4:
value << 2