Docsity

Bit Manipulation: A Tutorial by bmerry on Topcoder, Study Guides, Projects, Research of Data Structures and Algorithms

Toggle sidebar
bg1
12/24/2015 ABitofFun:FunwithBits–topcoder
https://www.topcoder.com/community/datascience/datasciencetutorials/abitoffunfunwithbits/ 1/7
FIND MEMBERS
JOIN LOG IN
COMPETE
DESIGN CHALLENGES
DEVELOPMENT CHALLENGES
DATA SCIENCE CHALLENGES
COMPETITIVE PROGRAMMING
LEARN
GETTING STARTED
DESIGN
DEVELOPMENT
DATA SCIENCE
COMPETITIVE PROGRAMMING
COMMUNITY
OVERVIEW
PROGRAMS
FORUMS
STATISTICS
MENU JOIN
pf3
pf4
pf5

Partial preview of the text

Download Bit Manipulation: A Tutorial by bmerry on Topcoder and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity!

FIND MEMBERS

JOIN LOG IN

COMPETE

DESIGN CHALLENGES

DEVELOPMENT CHALLENGES

DATA SCIENCE CHALLENGES

COMPETITIVE PROGRAMMING

LEARN

GETTING STARTED

DESIGN

DEVELOPMENT

DATA SCIENCE

COMPETITIVE PROGRAMMING

COMMUNITY

OVERVIEW

PROGRAMS

FORUMS

STATISTICS

MENU JOIN

EVENTS

BLOG

A Bit of Fun: Fun with Bits

By bmerry– TopCoder Member Discuss this article in the forums

Introduction Most of the optimizations that go into TopCoder challenges are high-level; that is, they affect the algorithm rather than the implementation. However, one of the most useful and effective low-level optimizations is bit manipulation, or using the bits of an integer to represent a set. Not only does it produce an order-of-magnitude improvement in both speed and size, it can often simplify code at the same time.

I’ll start by briefly recapping the basics, before going on to cover more advanced techniques.

The basics At the heart of bit manipulation are the bit-wise operators & (and), | (or), ~ (not) and ^ (xor). The first three you should already be familiar with in their boolean forms (&&, || and !). As a reminder, here are the truth tables:

A B !A A && B A || B A ^ B

The bit-wise versions of the operations are the same, except that instead of interpreting their arguments as true or false, they operate on each bit of the arguments. Thus, if A is 1010 and B is 1100, then

A & B = 1000

A | B = 1110

A ^ B = 0110

~A = 11110101 (the number of 1′s depends on the type of A).

Finally, there is a portable method that performs well in cases where the looping solution would require many iterations. Use each byte of the 4- or 8-byte integer to index a precomputed 256-entry table that stores the index of the highest (lowest) set bit in that byte. The highest (lowest) bit of the integer is then the maximum (minimum) of the table entries. This method is only mentioned for completeness, and the performance gain is unlikely to justify its use in a TopCoder match.

Counting out the bits One can easily check if a number is a power of 2: clear the lowest 1 bit (see above) and check if the result is 0. However, sometimes it is necessary to know how many bits are set, and this is more difficult.

GCC has a function called __builtin_popcount which does precisely this. However, unlike __builtin_ctz, it does not translate into a hardware instruction (at least on x86). Instead, it uses a table-based method similar to the one described above for bit searches. It is nevertheless quite efficient and also extremely convenient.

Users of other languages do not have this option (although they could re-implement it). If a number is expected to have very few 1 bits, an alternative is to repeatedly extract the lowest 1 bit and clear it.

All the subsets A big advantage of bit manipulation is that it is trivial to iterate over all the subsets of an N-element set: every N-bit value represents some subset. Even better, if A is a subset of B then the number representing A is less than that representing B, which is convenient for some dynamic programming solutions.

It is also possible to iterate over all the subsets of a particular subset (represented by a bit pattern), provided that you don’t mind visiting them in reverse order (if this is problematic, put them in a list as they’re generated, then walk the list backwards). The trick is similar to that for finding the lowest bit in a number. If we subtract 1 from a subset, then the lowest set element is cleared, and every lower element is set. However, we only want to set those lower elements that are in the superset. So the iteration step is just i = (i ‐ 1) & superset.

Even a bit wrong scores zero There are a few mistakes that are very easy to make when performing bit manipulations. Watch out for them in your code.

  1. When executing shift instructions for a << b, the x86 architecture uses only the bottom 5 bits of b (6 for 64- bit integers). This means that shifting left (or right) by 32 does nothing, rather than clearing all the bits. This behaviour is also specified by the Java and C# language standards; C99 says that shifting by at least the size of the value gives an undefined result. Historical trivia: the 8086 used the full shift register, and the change in behaviour was often used to detect newer processors.
  2. The & and | operators have lower precedence than comparison operators. That means that x & 3 == 1 is interpreted as x & (3 == 1), which is probably not what you want.
  3. If you want to write completely portable C/C++ code, be sure to use unsigned types, particularly if you plan to use the top-most bit. C99 says that shift operations on negative values are undefined. Java only has signed types: >> will sign-extend values (which is probably not what you want), but the Java-specific operator >>>

will shift in zeros.

Cute tricks There are a few other tricks that can be done with bit manipulation. They’re good for amazing your friends, but generally not worth the effect to use in practice. Reversing the bits in an integer

x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1); x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2); x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4); x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8); x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);

As an exercise, see if you can adapt this to count the number of bits in a word. Iterate through all k-element subsets of {0, 1, … N-1}

int s = (1 << k) ‐ 1; while (!(s & 1 << N)) { // do stuff with s int lo = s & ~(s ‐ 1); // lowest one bit int lz = (s + lo) & ~s; // lowest zero bit above lo s |= lz; // add lz to the set s &= ~(lz ‐ 1); // reset bits below lz s |= (lz / lo / 2) ‐ 1; // put back right number of bits at end }

In C, the last line can be written as s |= (lz >> ffs(lo)) ‐ 1 to avoid the division. Evaluate x? y : ‐y, where x is 0 or 1

(‐x ^ y) + x

This works on a twos-complement architecture (which is almost any machine you find today), where negation is done by inverting all the bits then adding 1. Note that on i686 and above, the original expression can be evaluated just as efficiently (i.e., without branches) due to the CMOVE (conditional move) instruction.

Sample problems TCCC 2006, Round 1B Medium For each city, keep a bit-set of the neighbouring cities. Once the part-building factories have been chosen (recursively), ANDing together these bit-sets will give a bit-set which describes the possible locations of the part-

© 2015 Topcoder. All Rights Reserved

SITEMAP

ABOUT US

CONTACT US

HELP CENTER

PRIVACY POLICY

TERMS

OTHERS

Topcoder is also on

if (i & (i << 1)) continue; pg.push_back(i); pgb.push_back(__builtin_popcount(i)); }

Member Tutorials Read more than 40 data science tutorials written by topcoder members.

Problem Set Analysis Read editorials explaining the problem and solution for each Single Round Match (SRM).

Data Science Guide New to topcoder's data science track? Read this guide for an overview on how to get started in the arena and how competitions work.

Help Center Need specifics about the process or the rules? Everything you need to know about competing at topcoder can be found in the Help Center.

Member Forums Join your peers in our member forums and ask questions from the real experts - topcoder members!

More Resources