Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

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. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...