Bit Manipulation

Bitwise operators

~NOT: bitwise NOT, or complement

  ~ 0111  (decimal 7)
  = 1000  (decimal 8)
  ~ 10101011
  = 01010100

&AND: bitwise AND

    0101 (decimal 5)
  & 0011 (decimal 3)
  = 0001 (decimal 1)

|OR: bitwise OR

   0101 (decimal 5)
 | 0011 (decimal 3)
 = 0111 (decimal 7)

^XOR: bitwise XOR

    0101 (decimal 5)
  ^ 0011 (decimal 3)
  = 0110 (decimal 6)

Bit shifts

A left arithmetic shift by n is equivalent to multiplying by 2^n (provided the value does not overflow), while a right arithmetic shift by n of a two's complement value is equivalent to dividing by 2^n and rounding toward negative infinity. If the binary number is treated as ones' complement, then the same right-shift operation results in division by 2^n and rounding toward zero.

This example uses an 8-bit register shit 1 bit:

LEFT-SHIFT:

   00010111 (decimal +23)  
=  00101110 (decimal +46)
   (23 << 1) = 23 * (2 ^ 1) = 46

RIGHT-SHIFT:

   10010111 (decimal −105) 
=  11001011 (decimal −53)
   (-105 >> 1) = -105 / (2 ^ 1) = -53

Basics

Set Union A I B
Set Intersection A & B
Set Subtraction A & ~B
Set Negation ALL_BITS ^ A or ~A
Set bit A I= (1 << bit)
Clear bit A &= (1 << bit)
Test bit A & (1 << bit) != 0 or (A >> bit) & 1 != 0
Extract Last bit(1) A & -A or A & ~(A-1) or A ^(A&(A-1))
Remove Last bit(1) A & (A - 1)
Get All 1-bits ~0

results matching ""

    No results matching ""