How undefined are __builtin_ctz(0) or __builtin_clz(0)?

Unfortunately, even x86-64 implementations can differ – from Intel’s instruction set reference,BSF and BSR, with a source operand value of (0), leaves the destination undefined, and sets the ZF (zero flag). So the behaviour may not be consistent between micro-architectures or, say, AMD and Intel. (I believe AMD leaves the destination unmodified.) The newer LZCNT … Read more

How is this bitwise AND operator masking the lower seven order bits of the number?

The number 0177 is an octal number representing the binary pattern below: 0000000001111111 When you AND it using the bitwise operation &, the result keeps the bits of the original only in the bits that are set to 1 in the “mask”; all other bits become zero. This is because “AND” follows this rule: X … Read more

why is 1>>32 == 1?

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.1 15.19 Shift Operators If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (ยง15.22.1) with the mask value 0x1f. The shift distance actually … Read more

Why in Java (high + low) / 2 is wrong but (high + low) >>> 1 is not?

In short, (high + low) >>> 1 is a trick that uses the unused sign-bit to perform a correct average of non-negative numbers. Under the assumption that high and low are both non-negative, we know for sure that the upper-most bit (the sign-bit) is zero. So both high and low are in fact 31-bit integers. … Read more