In C bits, multiply by 3 and divide by 16

后端 未结 5 633
孤独总比滥情好
孤独总比滥情好 2020-12-29 17:46

A buddy of mine had these puzzles and this is one that is eluding me. Here is the problem, you are given a number and you want to return that number times 3 and divided by 1

5条回答
  •  猫巷女王i
    2020-12-29 18:00

    what you can do is first divide by 4 then add 3 times then again devide by 4.

    3*x/16=(x/4+x/4+x/4)/4
    

    with this logic the program can be

    main()
    {
       int x=0xefffffff;
       int y;
       printf("%x",x);
       y=x&(0x80000000);
       y=y>>31;
       x=(y&(~x+1))+(~y&(x));
       x=x>>2;
       x=x&(0x3fffffff);
       x=x+x+x;
       x=x>>2;
       x=x&(0x3fffffff);
        x=(y&(~x+1))+(~y&(x));
       printf("\n%x %d",x,x);
    }
    

    AND with 0x3fffffff to make msb's zero. it'l even convert numbers to positive. This uses 2's complement of negative numbers. with direct methods to divide there will be loss of bit accuracy for negative numbers. so use this work arround of converting -ve to +ve number then perform division operations.

提交回复
热议问题