Having trouble trying to solve bit level manipulation puzzle in C -
so have use bitwise manipulation solve problem.
should duplicate effect of c expression (x*63), including overflow behavior. examples: multi63(1) = 63 multi63(-1) = -63 available ops: ! ~ & ^ | + << >>
maybe i'm not understanding being looked im trying different variations , each time result either close needs returned isn't correct.
this playing with. figured if mask x, 1 perimeter, know whether i'm multiplying negative or positive.
int y = x>>31; return ~(y^x)
this returns:
test times63(2147483647[0x7fffffff]) failed... ...gives -2147483648[0x80000000]. should 2147483585[0x7fffffc1]
and if try return 2147483585[0x7fffffc1] tells me need return -2147483648[0x80000000] i'm confused need return.
as general(!) rule can consider these formulas expression x*n, using shifts , addition/subtraction only:
a: (x << n) + (x << n-1) << + ... + << (x << m)
b: (x << n+1) - (x << m)
n can viewed sequence of 0's , 1's [(0...0)(1...1)(0...0)(1...1)]. have consider runs of 1's bit position n
down bit position m
, n == m possible.
in case n = 63, 011_1111 in binary. have n = 5 , m = 0. simple example assume x = 2:
using b: (2 << 6) - (2 << 0) == (2*64) - (2*1) == 128 - 2 == 126 (you can try out yourself, works fine.)
just demonstrate process on number, assume n = 55 , x = 2. 55 in binary: 011_0111. time have 2 sequences of 1's. n1 = 5, m1 = 4 , n2 = 2 , m2 = 0.
using b n1/m1: (2 << 6) - (2 << 4) == (2*64) - (2*16) == 128 - 32 == 96
using b n2/m2: (2 << 3) - (2 << 0) == (2*8) - (2*1) == 16 - 2 == 14
adding both results yields 110, desired value.
Comments
Post a Comment