next multiple of 8
Write an algorithm to compute the next multiple of 8 for a given
positive integer using bitwise operators.
Example,
(a) For the number 12, the next multiple of 8 is 16.
(b) For the number 16, the next multiple of 8 is 24.
positive integer using bitwise operators.
Example,
(a) For the number 12, the next multiple of 8 is 16.
(b) For the number 16, the next multiple of 8 is 24.
let the number be n
ReplyDeletesubtract the remainder when n is divided by 8
by x=n&(OxFFF8)
now x will be the multiple of 8 but we need to find the next multiple of 8
so add 8 to x
final ans=> x=x+8
regards
ankit
@ankit yeah it will work perfect.i was thinking of similar kind of solution,if first three bits are set on and then we add 1 to it to make it divisible by 8.
ReplyDeleteeg: x = (x|7) +1
x=x>>3;
ReplyDeletex++;
x=x<<3;
Is it correct ?
@navin it will work...
ReplyDelete