Bit twiddling: which bit is set?

Finally an optimal solution. See the end of this section for what to do when the input is guaranteed to have exactly one non-zero bit: http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn Here’s the code: static const int MultiplyDeBruijnBitPosition2[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, … Read more

Set a specific bit in an int

If you have an int value “intValue” and you want to set a specific bit at position “bitPosition“, do something like: intValue = intValue | (1 << bitPosition); or shorter: intValue |= 1 << bitPosition; If you want to reset a bit (i.e, set it to zero), you can do this: intValue &= ~(1 << … Read more

Flags enum & bitwise operations vs. “string of bits”

Benefits of using Flags enum: Standard approach: “They are the correct design to use when multiple enumeration values can be specified at the same time.” Intent is clear Maintainable — new programmers should pick this up easily Easily extensible — support for new flag combinations (e.g. weekend) Fast Negatives of using Flags enum: Data representation … Read more

Should I bit-shift to divide by 2 in Java? [duplicate]

Unless you’re working in a shop and a codebase where bit-shifting is common then, IMHO, you’re risking obfuscation. Yes, the expressions may be logically equivalent but: A n00b might get confused by the alternate syntax An old guy who hasn’t had to do any bit-shifting since college, like myself, might get confused If you bit … Read more

What is the efficient way to count set bits at a position or lower?

This C++ gets g++ to emit very good x86 ASM (godbolt compiler explorer). I expect it will compile efficiently on other 64bit architectures, too (if there’s a HW popcount for std::bitset::count to use, otherwise that’ll always be the slow part; e.g. sure to use g++ -march=nehalem or higher, or -mpopcnt if you don’t want to … Read more

bitwise & doesn’t work with bytes in kotlin

Kolin provides bitwise operator-like infix functions available for Int and Long only. So it’s necessary to convert bytes to ints to perform bitwise ops: val b : Byte = 127 val res = (b.toInt() and 0x0f).toByte() // evaluates to 15 UPDATE: Since Kotlin 1.1 these operations are available directly on Byte. From bitwiseOperations.kt: @SinceKotlin(“1.1”) public … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)