Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Shengliang/1386bea4d941c56a102d194982fc16b3 to your computer and use it in GitHub Desktop.
Save Shengliang/1386bea4d941c56a102d194982fc16b3 to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
//Ref: http://www.slideshare.net/gkumar007/bits-next-higher-presentation
/*
x CAFE01F0
-x 3501FE10
smallest:x &-x 00000010
ripple:x+ (x&-x) CAFE0200
ones:x ^ (x + (x&-x)) 000003F0
ones>>2 000000FC
ones >> 2/smallest 0000000F
ripple | ones CAFE020F
next higher CAFE020F
*/
uint32_t get_next_higher_number_with_same_number_of_ones(uint32_t x) {
printf("%20s %08X\n", "x", x);
printf("%20s %08X\n", "-x", -x);
uint32_t smallest = x & -x;
printf("%20s %08X\n", "smallest:x &-x", smallest);
uint32_t ripple = x + smallest;
printf("%20s %08X\n", "ripple:x+ (x&-x)", ripple);
uint32_t ones = x ^ ripple;
printf("%20s %08X\n", "ones:x ^ (x + (x&-x))", ones);
printf("%20s %08X\n", "ones>>2", ones>>2);
ones = (ones >> 2)/smallest;
printf("%20s %08X\n", "ones >> 2/smallest", ones);
x = (ripple | ones);
printf("%20s %08X\n", "ripple | ones", x);
return x;
}
int main(void) {
uint32_t x = 0xCAFE01F0;
printf("%20s %08X\n", "next higher", get_next_higher_number_with_same_number_of_ones(x));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment