To determine uniformity, the number must be in the form 00011111 or 11110000 . Consider the first (zeros followed by ones).
Add a value to the value. If it is uniform, it will have exactly one bit 1 , which means power 2.
To check if a value is a power of two, use (x & (x - 1)) == 0 . To shorten the code, we do not need to add it in the previous step. Instead, we check (x & (x + 1)) == 0
Apply this to another case, NOT specifying the initial value and repeat the process described above.
#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; }
source share