Be Bitwise!



Be Bitwise!

0 0


bitwise_presentation


On Github gypsydave5 / bitwise_presentation

Be Bitwise!

Created by David Wickes / gypsydave5

&&

true && false == false

5 && 2 == 2

'Level' && 'Up' == 'Up'

||

true || false == true

5 || 2 == 5

'Level' || 'Up' == 'Level'

But...

Why `||` ? Why && ?

What about | and & ?

How to Count in Binary

Binary Decimal 0 0 1 1 10 2 11 3 100 4 101 5 111 7
Binary Decimal 1000 8 10000 16 100000 32 1010 10 11111 31 1001000 72 101010 42

Back to those &s

  2.to_s(2)       # => "010"
  5.to_s(2)       # => "101"
  (5 & 2).to_s(2) # => "000"
          

AKA '0'

  2.to_s(2)       # => "010"
  5.to_s(2)       # => "101"
  (5 | 2).to_s(2) # => "111"
          

AKA '7'

Level 2!

`^` - XOR

`<<` - BITSHIFT LEFT

`>>` - BITSHIFT RIGHT

XOR

  7.to_s(2)       # => "111"
  4.to_s(2)       # => "100"
  (5 ^ 2).to_s(2) # => "011"
          

BITSHIFT

  7.to_s(2)        # => "0111"
  (7 << 1).to_s(2) # => "1110"
          

AKA 14

  4.to_s(2)        # => "100"
  (4 >> 2).to_s(2) # => "001"
          

AKA 2

Level 3!

`~` - NOT

(AKA BITFLIP)

DON'T

PANIC

TWO'S COMPLEMENT

Binary Decimal 0001 1 0101 5 0111 7 0000 0 1111 -1 1110 -2 1100 -4 1000 -8

WHAT'S IT ALL FOR?

QUESTION 1

Write a test to show a number is a power of 2.

Show your working.

  def iterate_power_of_two?(number)
    counter = 2
    while number > counter do
      counter*=2
    end
    return counter == number
  end
          

  def perfect_power_of_two?(number)
    number & (number - 1) == 0
  end
          

QUESTION 2

Write a test to show a directory can only be accessed by its owner.

Screw the working

  it 'can only be accessed by its owner' do
    permissions = File.stat(folder).mode
    expect(permissions & 0000100).to eq(64)
    expect(permissions & 0000010).to eq(0)
    expect(permissions & 0000001).to eq(0)
  end
          

THE END

David Wickes / gypsydave5

#YOHORT