Skip to content

Instantly share code, notes, and snippets.

@hartleybrody
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hartleybrody/9726672 to your computer and use it in GitHub Desktop.
Save hartleybrody/9726672 to your computer and use it in GitHub Desktop.
While learning about XORs during a basic crypto class, I decided to take a side track and learn about a term that was always shrouded in mystery -- bitwise operators. As always, I wrote these as my own notes for later reference but I'm publishing them here in case they help other people. Happy to accept pull requests for corrections.

(A bit of a tangent from crypto 101)

Bits and bytes

  • Core contepts:

    • Bitwise operators work on bits.
    • Bits are used to express data in binary form.
    • Bits can have a value of either 1 (ie TRUE) or 0 (ie FALSE).
  • Higher-level language constructs like floats and strings can all be represented as a series of bytes

    • 1 byte = 8 bits
      • ie 1100 1001
      • Each bit has two states (TRUE or FALSE) and there are 8 bites per byte
    • 2 ^ 8 = 256
      • two possible states for each bit, eight bits combined together
      • each byte can contain 256 possible values (between 0-255)
      • data structures that can take more than 256 values need to be stored using multiple bytes

Bitwise Operators

  • Bitwise Operators operate on the binary representation of their inputs

    • That’s why sometimes the results of the operations don’t seem to make any sense to a human
    • examples below
  • When you apply a bitwise operator on two inputs

    • it lines up each of the bits contained in the inputs’ bytes and compares them using the chosen bitwise operator
    • the comparison goes down the line, comparing each set of two bits and returning the result

Operators:

  • AND — returns TRUE (1) if both bits are the same
  • OR — returns TRUE (1) if either bit is TRUE (1)
  • XOR — returns TRUE (1) if only one of the bits is TRUE (1) or FALSE (0) if they’re the same
  • NOT — returns TRUE (1) if its input is FALSE (0) [only takes one input?]

201 AND 15:

        201: 1100 1001
    AND  15: 0000 1111
    ------------------
    IS   9  0000 1001

10 OR 12:

    10 | 12
    
    1010 #decimal 10
    1100 #decimal 12
    
    1110 #result = 14

Make sense? See also for more examples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment