Formula for Repetitive Constants
Sometimes, when dealing with masks, you need a constant that repeats every few bits. For instance, 0x0F0F0F0F selects the rightmost 4 bits of each byte in a 32-bit word. Extended to 64 bits, such constants can be tedious to write, and it's easy to miscount digits. The following formula is handy for writing such a constant of type long that repeats a value K every N bits, when the word size is a multiple of N: ~0UL/((1<<N)-1)*K.
For example, ~0UL/255*0xF generates the mask for the rightmost 4 bits of each byte in a long, as long as the number of bits in a long is a multiple of 8. The formula works because ~0UL/ ((1<<N)-1) in binary is a sequence of 1s with period N, for reasons similar to those that cause 9999/9 to generate a sequence of 1s in decimal.
A.R.