For your definition of uniform, the number has to be in the form 00011111
or 11110000
. Consider the former one (zeros followed by ones).
Add one to the value. If it is uniform, it would have exactly one 1
bit, which means a power of 2.
To test whether a value is a power of two, use (x & (x - 1)) == 0
. To shorten the code we don't need to add one in the previous step. Instead we check (x & (x + 1)) == 0
Apply this to the other case by NOT-ing the initial value and repeat the above process.
#include <cstdio>
bool isuniform(unsigned char x) {
unsigned char y = ~x;
return (x & (x + 1)) == 0 || (y & (y + 1)) == 0;
}
int main() {
printf("%d\n", isuniform(0)); // 00000000
printf("%d\n", isuniform(1)); // 00000001
printf("%d\n", isuniform(3)); // 00000011
printf("%d\n", isuniform(7)); // 00000111
printf("%d\n", isuniform(15)); // 00001111
printf("%d\n", isuniform(31)); // 00011111
printf("%d\n", isuniform(63)); // 00111111
printf("%d\n", isuniform(127)); // 01111111
printf("%d\n", isuniform(255)); // 11111111
printf("%d\n", isuniform(254)); // 11111110
printf("%d\n", isuniform(252)); // 11111100
printf("%d\n", isuniform(248)); // 11111000
printf("%d\n", isuniform(240)); // 11110000
printf("%d\n", isuniform(224)); // 11100000
printf("%d\n", isuniform(192)); // 11000000
printf("%d\n", isuniform(128)); // 10000000
//----------
printf("%d\n", isuniform(2));
printf("%d\n", isuniform(4));
printf("%d\n", isuniform(50));
printf("%d\n", isuniform(123));
printf("%d\n", isuniform(129));
printf("%d\n", isuniform(253));
return 0;
}