Efficient bitwise operations for counting bits or find the right|left most ones

If you want the fastest way, you will need to use non-portable methods. Windows/MSVC: _BitScanForward() _BitScanReverse() __popcnt() GCC: __builtin_ffs() __builtin_ctz() __builtin_clz() __builtin_popcount() These typically map directly to native hardware instructions. So it doesn’t get much faster than these. But since there’s no C/C++ functionality for them, they’re only accessible via compiler intrinsics.

How can I cast an int to a bit in MySQL 5.1?

You cannot! CAST and CONVERT only work to: BINARY[(N)] CHAR[(N)] DATE DATETIME DECIMAL[(M[,D])] SIGNED [INTEGER] TIME UNSIGNED [INTEGER] No room for: BIT, BITINT, TINYINT, MEDIUMINT, BIGINT, SMALLINT, … However, you can create your own function cast_to_bit(n): DELIMITER $$ CREATE FUNCTION cast_to_bit (N INT) RETURNS bit(1) BEGIN RETURN N; END To try it yourself, you can … Read more

Find out number of bits needed to represent a positive integer in binary?

Well, the answer is pretty simple. If you have an int value: int log2(int value) { return Integer.SIZE-Integer.numberOfLeadingZeros(value); } The same exists for Long… [Edit] If shaving milliseconds is an issue here, Integer.numberOfLeadingZeros(int) is reasonably efficient, but still does 15 operations… Expanding a reasonable amount of memory (300 bytes, static) you could shave that to … Read more

What does “real*8” mean?

The 8 refers to the number of bytes that the data type uses. So a 32-bit integer is integer*4 along the same lines. A quick search found this guide to Fortran data types, which includes: The “real*4” statement specifies the variable names to be single precision 4-byte real numbers which has 7 digits of accuracy … Read more

C/C++ efficient bit array

Since you mention C as well as C++, I’ll assume that a C++-oriented solution like boost::dynamic_bitset might not be applicable, and talk about a low-level C implementation instead. Note that if something like boost::dynamic_bitset works for you, or there’s a pre-existing C library you can find, then using them can be better than rolling your … Read more