Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Bithack for Bitmapped Memory Manager

Name: Anonymous 2012-03-28 12:53

Does anyone know a "bithack" (for lack of a better word, preferably a one or two line operation) for detecting the first set (or unset, either way) bit in an integer? In other words, if I have an integer like so:
0b00110101
and apply the "bithack" operation to it, it would return something like:
0b00100000
I understand that the effect will probably depend on the endianness of my processor's architecture. If there is a faster version that instead returns the first unset bit, that'd be ok as well.

Why do I want to know this?
I'm writing a simple bitmapped memory manager for managing a constant-size region of memory that has been separated into equally-sized chunks. You can easily memory in this way with a bitmap, one bit for each chunk (or # of chunks / 8 bytes of memory). A 0 indicates a free chunk, and a 1 indicates a chunk currently in use (or vice-versa, if it's easier to program that way). "Allocating" new chunks within this block of memory is easy, then: Find the first unset bit in the bitmap, mark it as set, and transform it into the address of the chunk. To free, do the opposite: Take the address of the chunk, get the corresponding bit, and unset it.

It's a trivial problem to solve if you use a byte, the smallest machine-addressable data size, to store each bit of the bitmap, but that uses 8x the memory that would have been used with a single bit per chunk approach, while possibly being slower.

With a single bit per chunk, I can easy find the first word with an unset bit (if a word has no unset bits, it should equal 0xFFFFFFFF, or equal 0 if it has no set bits), it's just the process of finding the first unset/set bit that I'm having trouble doing without being totally naive and using a billion branches. Any thoughts, /prog/?

Name: Anonymous 2012-03-29 20:05

>>11-14 back to /g/, please.

>>9 I figured it out myself.

http://en.wikipedia.org/wiki/Find_first_set

It turns out, many popular compilers (including GCC) include a library of functions for things like counting leading zeroes or finding the first set bit. These exist entirely so that programmers who need processor-specific features like this can get them without having to use inline assembly and break portability (at least among architectures; using GCC's functions will still prevent you from using other compilers). I'm assuming that if I, say, use a prebuilt function for finding the first set bit and my processor only supports counting the leading zeroes, it will automatically handle the complex task of incrementing the result by one for me.

This is really fascinating, I had no idea that C compilers had features like this. I'm glad I posted this thread, and thank >>4 for his mention of the specific opcodes.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List