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.

Comments

  1. let the number be n
    subtract 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

    ReplyDelete
  2. @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.
    eg: x = (x|7) +1

    ReplyDelete
  3. x=x>>3;
    x++;
    x=x<<3;
    Is it correct ?

    ReplyDelete

Post a Comment

Popular posts from this blog