Bit Maniplation
Bit Maniplation
Micah Stairs
Outline
• Overview
• Bitwise Operators
• Bit Operations
• Sets of Elements
• BitSet Class
100100112 = 14710
( 1 x 27 + 0 x 2 6 + 0 x 2 5 + 1 x 2 4 + 0 x 23 + 0 x 22 + 1 x 21 + 1 x 20)
Integers and Longs
Integers and Longs
Invalid:
Valid:
Valid:
Integers and Longs
NOT AND
1 0 1 0 1 0 1 1 0 1 0
1 0 1 0 1 0
1 …1 0 1 0 1 0 1
1 0 1 0
OR XOR
1 1 0 1 0 1 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0
1 1 1 0 1 0 1 1 0 0 0 0
Bit Shifting to the Left
Outputs: “101100”
Outputs: “10000000000000000000000000000000”
Outputs: “101”
Outputs: “10”
Outputs “11111111111111111111111111111111”
Outputs “11111111111111111111111111111111”
Outputs “1111111111111111”
Bit Operations
Basic Bit Operations
These are some of the
most common
operations that you
will need to do
when dealing with
a set of bits.
Note: 2n = 1 << n
Advanced Bit Operations
But there are lots of other cool things that can be done.
Outputs “10011”
BitSet Class
BitSet Class
If you need more than 64 bits you can either
use multiple int / long values, or you can take
advantage of the BitSet class (arbitrary
number of bits).
Internally, this class stores the bits in a series
of long values (although you do not have direct
access to these values).
This class has all of the methods that you
might expect.
Solution Sketch
Geppetto
https://open.kattis.com/problems/geppetto
• https://docs.oracle.com
• https://docs.oracle.com/javase/tutorial/java/
nutsandbolts/op3.html
• http://docs.oracle.com/javase/7/docs/technotes/
guides/language/binary-literals.html
• https://open.kattis.com/problems/geppetto