A way to invert the binary value of a integer variable

后端 未结 6 540
忘掉有多难
忘掉有多难 2020-12-10 10:44

I have this integer int nine = 9; which in binary is 1001. Is there an easy way to invert it so I can get 0110 ?

6条回答
  •  旧巷少年郎
    2020-12-10 11:25

    This problem is not completely specified - do you only care about 4 bits, or should the answer adjust to the number of significant bits in the input? If it's the latter then you'll need some sophisticated bit manipulation to mask off the upper bits.

    I'll slightly modify a Bit Twiddling Hack to create the mask.

    int mask = num;
    mask |= mask >> 1;
    mask |= mask >> 2;
    mask |= mask >> 4;
    mask |= mask >> 8;
    mask |= mask >> 16;
    int inverse = ~num & mask;
    

    See it in action: http://ideone.com/pEqwwM

提交回复
热议问题