See example No. 156 below. I also published a source for a detailed explanation.
{
x = 156 10011100 becomes 10100011 To get the next higher number we need to set the 6th bit from LSB and shift the string of 1 (3rd,4th,5th) to LSB positions 1,2 and drop 5th bit
therefore, we get 163 - 10100011, which is the next largest number with the same number 1 as 156.
00011100 - right most string of 1 in x 00000011 - right shifted pattern except left most bit ------> [A] 00010000 - isolated left most bit of right most 1 pattern 00100000 - shiftleft-ed the isolated bit by one position ------> [B] 10000000 - left part of x, excluding right most 1 pattern ------> [C] 10100000 - add B and C (OR operation) ------> [D] 10100011 - add A and D which is required number 163
}
{
uint_t snoob(uint_t x) { uint_t rightOne; uint_t nextHigherOneBit; uint_t rightOnesPattern; uint_t next = 0; if(x){
}
source: http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
source share