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

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

Bit manipulations good practices

The problem with bit fields is that the C standard does not dictate that the order in which they are defined is the same as the order that they are implemented. So you may not be setting the bits you think you are. Section 6.7.2.1p11 of the C standard states: An implementation may allocate any … 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 … Read more

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