0% found this document useful (0 votes)
17 views34 pages

Bit Maniplation

The document discusses bit manipulation concepts in computer science and competitive programming. It covers binary numbers, integer and long data types, bitwise operators, basic and advanced bit operations, using bits to represent sets of elements, and the BitSet class. It also provides an example solution sketch for counting valid pizza combinations given bad ingredient pairs on Kattis.

Uploaded by

Aditya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views34 pages

Bit Maniplation

The document discusses bit manipulation concepts in computer science and competitive programming. It covers binary numbers, integer and long data types, bitwise operators, basic and advanced bit operations, using bits to represent sets of elements, and the BitSet class. It also provides an example solution sketch for counting valid pizza combinations given bad ingredient pairs on Kattis.

Uploaded by

Aditya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Bit Manipulation

Micah Stairs
Outline
• Overview

• Review of Binary Numbers

• Integers and Longs

• Bitwise Operators

• Bit Operations

• Sets of Elements

• BitSet Class

• Solution Sketch for a Kattis Problem


Overview
Bit manipulation is a fundamental concept in
Computer Science. In competitive programming,
bit manipulation has a number of applications:
• Representing information in a compact way
• Performing fast computations
• Representing sets of elements
Review of Binary
Numbers
As opposed to representing a number in the typical base-10
numeral system (with digits 0-9), the base-2 (or binary)
numeral system is represented using only the digits 0 and 1.

Each digit is referred to as a “bit”. The most significant bits


are on the left and the least significant bits are on the right.

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

In Java, an int is 32 bits and a long is 64 bits.

They are both ‘signed’, which means they have


a range of both positive and negative values
that can be represented.
Integers and Longs
The left-most bit is used to indicate whether
or not the number is negative, leaving the
remaining 31 or 63 bits to represent the value.
An int can represent a number in the range
[-231, 231-1].
A long can represent a number in the range
[-263, 263-1].
Integers and Longs
If any of your computations exceed the range
of your data type, then you will become a
victim of integer overflow. This will give you
unexpected (wrong) answers.

If in doubt, pick the larger data type. If long


isn’t large enough, you may need to resort to
the BigInteger class.
Integers and Longs
When initializing int (or long) variables, there is
more than one type of notation that can be
used. The following are equivalent:

The underscores can be added to improve


readability. The “0b” is used to indicate the
number will be specified in binary.
Integers and Longs
When initializing long variables which are
outside the bounds of what can fit inside an
int, the number must be followed by a
lowercase or uppercase “L” (preferably the
latter).

Forgetting to do so will cause a compilation


error.
Integers and Longs
When possible, it is best to use the primitive int and
long types as opposed to Integer and Long objects. The
primitive types use less space and are faster.
The main reason the object wrapper is useful is because
of generics. Primitive types cannot be used directly
inside generic classes since a reference is required.

Invalid:

Valid:
Valid:
Integers and Longs

Another reason to use the objects would be if


you need to use the “null” value.
The Integer and Long classes, however, contain
a number of static methods which take and
return primitive types.
Integers and Longs
Method Description

formats number as binary string


toBinaryString(value)
Ex: 37 -> “100101”

bitCount(value) counts bits

reverse(value) reverses the order of the bits

rotateLeft(value, distance) rotates bits (wrapping around)

rotateRight(value, distance) rotates bits (wrapping around)


Integers and Longs
Method Description

counts leading zeroes in bit


numberOfLeadingZeroes(value)
pattern
counts trailing zeroes in bit
numberOfTrailingZeroes(value)
pattern
clears all bits except
highestOneBit(value)
highest set bit
clears all bits except lowest
lowestOneBit(value)
set bit
Bitwise Operators
Bitwise Operators
Symbol Operation
~ NOT (negates bit pattern)
& AND
| inclusive OR
^ exclusive OR
<< signed left shift
>> signed right shift
>>> unsigned right shift
Unary and Binary Bitwise Operators

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”

Note: Shifting int values by more than 31 or long


values by more than 63 has undefined behaviour.
Bit Shifting to the Right

Outputs: “101”

Outputs: “10”

Note: The signed and unsigned right bit shifting behave


the same when working with positive values.
Bit Shifting to the Right

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.

How is this typically done


without bit manipulation?
Advanced Bit Operations
You can even swap two variables without creating
a new temporary variable.

Outputs “13” and then “7”


Sets of Elements
Bitset
In a set, each element appears either 0 or 1
times. This lends itself quite nicely to a
bitstring representation.
An int can represent up to 32 elements and a
long can represent up to 64 elements.
Each element will be assigned to a particular
bit in the number.
Combinations
Using bit manipulation, it is quite easy to iterate
over all possible combinations of some number
of elements. This is known as the power set.
Note: Looping over [0, 1 << n) is the same as
looping over all binary strings of length n.
Complement
Given some subset, you can also find the
complement (the missing elements).

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

Summary: Given a number of ingredients (up


to 20) and a list of bad pairs of ingredients (up
to 400), count the number of valid pizza
combinations.
Geppetto
Solution:

• Read in the input, storing each bad pair of


ingredients.

• Since there are only 20 ingredients we can


iterate over all combinations. For each
combination, we loop over all bad pairs of
ingredients. A combination is counted if it
doesn’t contain any of these bad pairs of
ingredients (checked using bit manipulation).
Sources

• 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

You might also like