I have to check a number if it satisfies the following criteria:
- in binary, all one-bits must be successive.
- the number must have at least one bit set.
- the successive one-bits may start at the MSB or end at the LSB, so it's perfectly valid if the number is made up of a single one-bit stream followed by a zero-bit stream or vice versa.
I wrote a code that checks for these conditions for a real-world problem (checking data-file integrity).
It works without problems and it's anything but time-critical, but I'm an old bit-twiddeling freak and love such puzzles, so I've tried to came up with a more clever way to check for single-one-bit streams.
Cases where the string is surrounded by zeros is easy, but that one can't deal with the special cases.
Any ideas, binary hacks and partial solutions are welcome!
To make my requirements more clear some examples: The following numbers satisfy my criteria:
0x80000000
0x00000001
0xff000000
0x000000ff
0xffffffff
0x000ff000
The following numbers don't (as they have more than one successive string of ones):
0xf00000f <- one-bit streams should not wrap-around at 2^n
0x0001700 <- a trivial example.
0x0000000 <- no one bit at all.