A way to invert the binary value of a integer variable

后端 未结 6 538
忘掉有多难
忘掉有多难 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:23

    int notnine = ~nine;
    

    If you're worried about only the last byte:

    int notnine = ~nine & 0x000000FF;
    

    And if you're only interested in the last nibble:

    int notnine = ~nine & 0x0000000F;
    

    The ~ operator is the bitwise negation, while the mask gives you only the byte/nibble you care about.

    If you truly are interested in only the last nibble, the most simple is:

    int notnine = 15 - nine;
    

    Works for every nibble. :-)

提交回复
热议问题