Skip to main content

Bitwise Operations

This block performs bitwise operations on integer values. Use it for bit manipulation, flag processing, and low-level data handling.

Bitwise Operations Block

Overview

The Bitwise Operations block manipulates individual bits in integer values, enabling low-level data processing and efficient flag handling.

Bitwise Operators

AND (&)

Sets bit to 1 only if both corresponding bits are 1:

  1010 (10)
& 1100 (12)
------
1000 (8)

OR (|)

Sets bit to 1 if either corresponding bit is 1:

  1010 (10)
| 1100 (12)
------
1110 (14)

XOR (^)

Sets bit to 1 if corresponding bits are different:

  1010 (10)
^ 1100 (12)
------
0110 (6)

Left Shift (<<)

Shifts bits left, filling with zeros:

1010 << 2 = 101000

Right Shift (>>)

Shifts bits right, discarding rightmost bits:

1010 >> 2 = 0010

Use Cases

Common bitwise operation scenarios:

Flag Manipulation

Check, set, or clear status flags:

// Check if bit 3 is set
is_set = (value & 0x08) != 0

// Set bit 3
value = value | 0x08

// Clear bit 3
value = value & ~0x08

// Toggle bit 3
value = value ^ 0x08

Bit Masking

Extract specific bits from value:

// Get lower 4 bits
lower_nibble = value & 0x0F

// Get upper 4 bits
upper_nibble = (value & 0xF0) >> 4

Register Configuration

Configure hardware registers:

// Set configuration bits
config = 0x00
config = config | 0x01 // Enable feature 1
config = config | 0x04 // Enable feature 3

Configuration

  • Operation: Bitwise operation type
  • Operand 1: First value
  • Operand 2: Second value (if required)
  • Output: Variable to store result

Applications

Status Byte Decoding

status = device_status_byte
motor_running = (status & 0x01) != 0
door_open = (status & 0x02) != 0
temp_alarm = (status & 0x04) != 0

Data Packing

// Pack 4 values into single byte
packed = (value1 & 0x03) |
((value2 & 0x03) << 2) |
((value3 & 0x03) << 4) |
((value4 & 0x03) << 6)

Checksum Calculation

checksum = byte1 ^ byte2 ^ byte3 ^ byte4

Common Patterns

Create Bit Mask

mask = (1 << num_bits) - 1
// For 4 bits: (1 << 4) - 1 = 0x0F

Check Range of Bits

bits_3_to_5 = (value >> 3) & 0x07

Swap Nibbles

swapped = ((value & 0x0F) << 4) | ((value & 0xF0) >> 4)

Debugging

Debug bitwise operations:

  • Print values in binary/hex
  • Verify bit positions
  • Test with simple cases
  • Check operator precedence

See Also